Bug Summary

File:tools/clang/lib/Analysis/BodyFarm.cpp
Warning:line 142, 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-eagerly-assume -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 -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.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-7~svn329677/build-llvm/tools/clang/lib/Analysis -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Analysis/BodyFarm.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Analysis/BodyFarm.cpp

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

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.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.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class LLVM_ALIGNAS(8)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")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 276, __extension__ __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 getLocStart() 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 getLocStart() 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())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 764, __extension__ __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 enum { NumVarDeclBits = 7 };
871
872protected:
873 enum { NumParameterIndexBits = 8 };
874
875 enum DefaultArgKind {
876 DAK_None,
877 DAK_Unparsed,
878 DAK_Uninstantiated,
879 DAK_Normal
880 };
881
882 class ParmVarDeclBitfields {
883 friend class ASTDeclReader;
884 friend class ParmVarDecl;
885
886 unsigned : NumVarDeclBits;
887
888 /// Whether this parameter inherits a default argument from a
889 /// prior declaration.
890 unsigned HasInheritedDefaultArg : 1;
891
892 /// Describes the kind of default argument for this parameter. By default
893 /// this is none. If this is normal, then the default argument is stored in
894 /// the \c VarDecl initializer expression unless we were unable to parse
895 /// (even an invalid) expression for the default argument.
896 unsigned DefaultArgKind : 2;
897
898 /// Whether this parameter undergoes K&R argument promotion.
899 unsigned IsKNRPromoted : 1;
900
901 /// Whether this parameter is an ObjC method parameter or not.
902 unsigned IsObjCMethodParam : 1;
903
904 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
905 /// Otherwise, the number of function parameter scopes enclosing
906 /// the function parameter scope in which this parameter was
907 /// declared.
908 unsigned ScopeDepthOrObjCQuals : 7;
909
910 /// The number of parameters preceding this parameter in the
911 /// function parameter scope in which it was declared.
912 unsigned ParameterIndex : NumParameterIndexBits;
913 };
914
915 class NonParmVarDeclBitfields {
916 friend class ASTDeclReader;
917 friend class ImplicitParamDecl;
918 friend class VarDecl;
919
920 unsigned : NumVarDeclBits;
921
922 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
923 /// Whether this variable is a definition which was demoted due to
924 /// module merge.
925 unsigned IsThisDeclarationADemotedDefinition : 1;
926
927 /// Whether this variable is the exception variable in a C++ catch
928 /// or an Objective-C @catch statement.
929 unsigned ExceptionVar : 1;
930
931 /// Whether this local variable could be allocated in the return
932 /// slot of its function, enabling the named return value optimization
933 /// (NRVO).
934 unsigned NRVOVariable : 1;
935
936 /// Whether this variable is the for-range-declaration in a C++0x
937 /// for-range statement.
938 unsigned CXXForRangeDecl : 1;
939
940 /// Whether this variable is the for-in loop declaration in Objective-C.
941 unsigned ObjCForDecl : 1;
942
943 /// Whether this variable is an ARC pseudo-__strong
944 /// variable; see isARCPseudoStrong() for details.
945 unsigned ARCPseudoStrong : 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
970 union {
971 unsigned AllBits;
972 VarDeclBitfields VarDeclBits;
973 ParmVarDeclBitfields ParmVarDeclBits;
974 NonParmVarDeclBitfields NonParmVarDeclBits;
975 };
976
977 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
978 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
979 TypeSourceInfo *TInfo, StorageClass SC);
980
981 using redeclarable_base = Redeclarable<VarDecl>;
982
983 VarDecl *getNextRedeclarationImpl() override {
984 return getNextRedeclaration();
985 }
986
987 VarDecl *getPreviousDeclImpl() override {
988 return getPreviousDecl();
989 }
990
991 VarDecl *getMostRecentDeclImpl() override {
992 return getMostRecentDecl();
993 }
994
995public:
996 using redecl_range = redeclarable_base::redecl_range;
997 using redecl_iterator = redeclarable_base::redecl_iterator;
998
999 using redeclarable_base::redecls_begin;
1000 using redeclarable_base::redecls_end;
1001 using redeclarable_base::redecls;
1002 using redeclarable_base::getPreviousDecl;
1003 using redeclarable_base::getMostRecentDecl;
1004 using redeclarable_base::isFirstDecl;
1005
1006 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1007 SourceLocation StartLoc, SourceLocation IdLoc,
1008 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1009 StorageClass S);
1010
1011 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1012
1013 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1014
1015 /// Returns the storage class as written in the source. For the
1016 /// computed linkage of symbol, see getLinkage.
1017 StorageClass getStorageClass() const {
1018 return (StorageClass) VarDeclBits.SClass;
1019 }
1020 void setStorageClass(StorageClass SC);
1021
1022 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1023 VarDeclBits.TSCSpec = TSC;
1024 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1024, __extension__ __PRETTY_FUNCTION__))
;
1025 }
1026 ThreadStorageClassSpecifier getTSCSpec() const {
1027 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1028 }
1029 TLSKind getTLSKind() const;
1030
1031 /// Returns true if a variable with function scope is a non-static local
1032 /// variable.
1033 bool hasLocalStorage() const {
1034 if (getStorageClass() == SC_None) {
1035 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1036 // used to describe variables allocated in global memory and which are
1037 // accessed inside a kernel(s) as read-only variables. As such, variables
1038 // in constant address space cannot have local storage.
1039 if (getType().getAddressSpace() == LangAS::opencl_constant)
1040 return false;
1041 // Second check is for C++11 [dcl.stc]p4.
1042 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1043 }
1044
1045 // Global Named Register (GNU extension)
1046 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1047 return false;
1048
1049 // Return true for: Auto, Register.
1050 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1051
1052 return getStorageClass() >= SC_Auto;
1053 }
1054
1055 /// Returns true if a variable with function scope is a static local
1056 /// variable.
1057 bool isStaticLocal() const {
1058 return (getStorageClass() == SC_Static ||
1059 // C++11 [dcl.stc]p4
1060 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1061 && !isFileVarDecl();
1062 }
1063
1064 /// Returns true if a variable has extern or __private_extern__
1065 /// storage.
1066 bool hasExternalStorage() const {
1067 return getStorageClass() == SC_Extern ||
1068 getStorageClass() == SC_PrivateExtern;
1069 }
1070
1071 /// Returns true for all variables that do not have local storage.
1072 ///
1073 /// This includes all global variables as well as static variables declared
1074 /// within a function.
1075 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1076
1077 /// Get the storage duration of this variable, per C++ [basic.stc].
1078 StorageDuration getStorageDuration() const {
1079 return hasLocalStorage() ? SD_Automatic :
1080 getTSCSpec() ? SD_Thread : SD_Static;
1081 }
1082
1083 /// Compute the language linkage.
1084 LanguageLinkage getLanguageLinkage() const;
1085
1086 /// Determines whether this variable is a variable with external, C linkage.
1087 bool isExternC() const;
1088
1089 /// Determines whether this variable's context is, or is nested within,
1090 /// a C++ extern "C" linkage spec.
1091 bool isInExternCContext() const;
1092
1093 /// Determines whether this variable's context is, or is nested within,
1094 /// a C++ extern "C++" linkage spec.
1095 bool isInExternCXXContext() const;
1096
1097 /// Returns true for local variable declarations other than parameters.
1098 /// Note that this includes static variables inside of functions. It also
1099 /// includes variables inside blocks.
1100 ///
1101 /// void foo() { int x; static int y; extern int z; }
1102 bool isLocalVarDecl() const {
1103 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1104 return false;
1105 if (const DeclContext *DC = getLexicalDeclContext())
1106 return DC->getRedeclContext()->isFunctionOrMethod();
1107 return false;
1108 }
1109
1110 /// Similar to isLocalVarDecl but also includes parameters.
1111 bool isLocalVarDeclOrParm() const {
1112 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1113 }
1114
1115 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1116 bool isFunctionOrMethodVarDecl() const {
1117 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1118 return false;
1119 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1120 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1121 }
1122
1123 /// Determines whether this is a static data member.
1124 ///
1125 /// This will only be true in C++, and applies to, e.g., the
1126 /// variable 'x' in:
1127 /// \code
1128 /// struct S {
1129 /// static int x;
1130 /// };
1131 /// \endcode
1132 bool isStaticDataMember() const {
1133 // If it wasn't static, it would be a FieldDecl.
1134 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1135 }
1136
1137 VarDecl *getCanonicalDecl() override;
1138 const VarDecl *getCanonicalDecl() const {
1139 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1140 }
1141
1142 enum DefinitionKind {
1143 /// This declaration is only a declaration.
1144 DeclarationOnly,
1145
1146 /// This declaration is a tentative definition.
1147 TentativeDefinition,
1148
1149 /// This declaration is definitely a definition.
1150 Definition
1151 };
1152
1153 /// Check whether this declaration is a definition. If this could be
1154 /// a tentative definition (in C), don't check whether there's an overriding
1155 /// definition.
1156 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1157 DefinitionKind isThisDeclarationADefinition() const {
1158 return isThisDeclarationADefinition(getASTContext());
1159 }
1160
1161 /// Check whether this variable is defined in this translation unit.
1162 DefinitionKind hasDefinition(ASTContext &) const;
1163 DefinitionKind hasDefinition() const {
1164 return hasDefinition(getASTContext());
1165 }
1166
1167 /// Get the tentative definition that acts as the real definition in a TU.
1168 /// Returns null if there is a proper definition available.
1169 VarDecl *getActingDefinition();
1170 const VarDecl *getActingDefinition() const {
1171 return const_cast<VarDecl*>(this)->getActingDefinition();
1172 }
1173
1174 /// Get the real (not just tentative) definition for this declaration.
1175 VarDecl *getDefinition(ASTContext &);
1176 const VarDecl *getDefinition(ASTContext &C) const {
1177 return const_cast<VarDecl*>(this)->getDefinition(C);
1178 }
1179 VarDecl *getDefinition() {
1180 return getDefinition(getASTContext());
1181 }
1182 const VarDecl *getDefinition() const {
1183 return const_cast<VarDecl*>(this)->getDefinition();
1184 }
1185
1186 /// Determine whether this is or was instantiated from an out-of-line
1187 /// definition of a static data member.
1188 bool isOutOfLine() const override;
1189
1190 /// Returns true for file scoped variable declaration.
1191 bool isFileVarDecl() const {
1192 Kind K = getKind();
1193 if (K == ParmVar || K == ImplicitParam)
1194 return false;
1195
1196 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1197 return true;
1198
1199 if (isStaticDataMember())
1200 return true;
1201
1202 return false;
1203 }
1204
1205 /// Get the initializer for this variable, no matter which
1206 /// declaration it is attached to.
1207 const Expr *getAnyInitializer() const {
1208 const VarDecl *D;
1209 return getAnyInitializer(D);
1210 }
1211
1212 /// Get the initializer for this variable, no matter which
1213 /// declaration it is attached to. Also get that declaration.
1214 const Expr *getAnyInitializer(const VarDecl *&D) const;
1215
1216 bool hasInit() const;
1217 const Expr *getInit() const {
1218 return const_cast<VarDecl *>(this)->getInit();
1219 }
1220 Expr *getInit();
1221
1222 /// Retrieve the address of the initializer expression.
1223 Stmt **getInitAddress();
1224
1225 void setInit(Expr *I);
1226
1227 /// Determine whether this variable's value can be used in a
1228 /// constant expression, according to the relevant language standard.
1229 /// This only checks properties of the declaration, and does not check
1230 /// whether the initializer is in fact a constant expression.
1231 bool isUsableInConstantExpressions(ASTContext &C) const;
1232
1233 EvaluatedStmt *ensureEvaluatedStmt() const;
1234
1235 /// \brief Attempt to evaluate the value of the initializer attached to this
1236 /// declaration, and produce notes explaining why it cannot be evaluated or is
1237 /// not a constant expression. Returns a pointer to the value if evaluation
1238 /// succeeded, 0 otherwise.
1239 APValue *evaluateValue() const;
1240 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1241
1242 /// \brief Return the already-evaluated value of this variable's
1243 /// initializer, or NULL if the value is not yet known. Returns pointer
1244 /// to untyped APValue if the value could not be evaluated.
1245 APValue *getEvaluatedValue() const;
1246
1247 /// \brief Determines whether it is already known whether the
1248 /// initializer is an integral constant expression or not.
1249 bool isInitKnownICE() const;
1250
1251 /// \brief Determines whether the initializer is an integral constant
1252 /// expression, or in C++11, whether the initializer is a constant
1253 /// expression.
1254 ///
1255 /// \pre isInitKnownICE()
1256 bool isInitICE() const;
1257
1258 /// \brief Determine whether the value of the initializer attached to this
1259 /// declaration is an integral constant expression.
1260 bool checkInitIsICE() const;
1261
1262 void setInitStyle(InitializationStyle Style) {
1263 VarDeclBits.InitStyle = Style;
1264 }
1265
1266 /// \brief The style of initialization for this declaration.
1267 ///
1268 /// C-style initialization is "int x = 1;". Call-style initialization is
1269 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1270 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1271 /// expression for class types. List-style initialization is C++11 syntax,
1272 /// e.g. "int x{1};". Clients can distinguish between different forms of
1273 /// initialization by checking this value. In particular, "int x = {1};" is
1274 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1275 /// Init expression in all three cases is an InitListExpr.
1276 InitializationStyle getInitStyle() const {
1277 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1278 }
1279
1280 /// \brief Whether the initializer is a direct-initializer (list or call).
1281 bool isDirectInit() const {
1282 return getInitStyle() != CInit;
1283 }
1284
1285 /// \brief If this definition should pretend to be a declaration.
1286 bool isThisDeclarationADemotedDefinition() const {
1287 return isa<ParmVarDecl>(this) ? false :
1288 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1289 }
1290
1291 /// \brief This is a definition which should be demoted to a declaration.
1292 ///
1293 /// In some cases (mostly module merging) we can end up with two visible
1294 /// definitions one of which needs to be demoted to a declaration to keep
1295 /// the AST invariants.
1296 void demoteThisDefinitionToDeclaration() {
1297 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) &&
"Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1298, __extension__ __PRETTY_FUNCTION__))
;
1299 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1300 }
1301
1302 /// \brief Determine whether this variable is the exception variable in a
1303 /// C++ catch statememt or an Objective-C \@catch statement.
1304 bool isExceptionVariable() const {
1305 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1306 }
1307 void setExceptionVariable(bool EV) {
1308 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1308, __extension__ __PRETTY_FUNCTION__))
;
1309 NonParmVarDeclBits.ExceptionVar = EV;
1310 }
1311
1312 /// \brief Determine whether this local variable can be used with the named
1313 /// return value optimization (NRVO).
1314 ///
1315 /// The named return value optimization (NRVO) works by marking certain
1316 /// non-volatile local variables of class type as NRVO objects. These
1317 /// locals can be allocated within the return slot of their containing
1318 /// function, in which case there is no need to copy the object to the
1319 /// return slot when returning from the function. Within the function body,
1320 /// each return that returns the NRVO object will have this variable as its
1321 /// NRVO candidate.
1322 bool isNRVOVariable() const {
1323 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1324 }
1325 void setNRVOVariable(bool NRVO) {
1326 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1326, __extension__ __PRETTY_FUNCTION__))
;
1327 NonParmVarDeclBits.NRVOVariable = NRVO;
1328 }
1329
1330 /// \brief Determine whether this variable is the for-range-declaration in
1331 /// a C++0x for-range statement.
1332 bool isCXXForRangeDecl() const {
1333 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1334 }
1335 void setCXXForRangeDecl(bool FRD) {
1336 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1336, __extension__ __PRETTY_FUNCTION__))
;
1337 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1338 }
1339
1340 /// \brief Determine whether this variable is a for-loop declaration for a
1341 /// for-in statement in Objective-C.
1342 bool isObjCForDecl() const {
1343 return NonParmVarDeclBits.ObjCForDecl;
1344 }
1345
1346 void setObjCForDecl(bool FRD) {
1347 NonParmVarDeclBits.ObjCForDecl = FRD;
1348 }
1349
1350 /// \brief Determine whether this variable is an ARC pseudo-__strong
1351 /// variable. A pseudo-__strong variable has a __strong-qualified
1352 /// type but does not actually retain the object written into it.
1353 /// Generally such variables are also 'const' for safety.
1354 bool isARCPseudoStrong() const {
1355 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1356 }
1357 void setARCPseudoStrong(bool ps) {
1358 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1358, __extension__ __PRETTY_FUNCTION__))
;
1359 NonParmVarDeclBits.ARCPseudoStrong = ps;
1360 }
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))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1371, __extension__ __PRETTY_FUNCTION__))
;
1372 NonParmVarDeclBits.IsInline = true;
1373 NonParmVarDeclBits.IsInlineSpecified = true;
1374 }
1375 void setImplicitlyInline() {
1376 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1376, __extension__ __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))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1385, __extension__ __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))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1394, __extension__ __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))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1406, __extension__ __PRETTY_FUNCTION__))
;
1407 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1408 }
1409
1410 /// \brief Retrieve the variable declaration from which this variable could
1411 /// be instantiated, if it is an instantiation (rather than a non-template).
1412 VarDecl *getTemplateInstantiationPattern() const;
1413
1414 /// \brief If this variable is an instantiated static data member of a
1415 /// class template specialization, returns the templated static data member
1416 /// from which it was instantiated.
1417 VarDecl *getInstantiatedFromStaticDataMember() const;
1418
1419 /// \brief If this variable is an instantiation of a variable template or a
1420 /// static data member of a class template, determine what kind of
1421 /// template specialization or instantiation this is.
1422 TemplateSpecializationKind getTemplateSpecializationKind() const;
1423
1424 /// \brief If this variable is an instantiation of a variable template or a
1425 /// static data member of a class template, determine its point of
1426 /// instantiation.
1427 SourceLocation getPointOfInstantiation() const;
1428
1429 /// \brief If this variable is an instantiation of a static data member of a
1430 /// class template specialization, retrieves the member specialization
1431 /// information.
1432 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1433
1434 /// \brief For a static data member that was instantiated from a static
1435 /// data member of a class template, set the template specialiation kind.
1436 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1437 SourceLocation PointOfInstantiation = SourceLocation());
1438
1439 /// \brief Specify that this variable is an instantiation of the
1440 /// static data member VD.
1441 void setInstantiationOfStaticDataMember(VarDecl *VD,
1442 TemplateSpecializationKind TSK);
1443
1444 /// \brief Retrieves the variable template that is described by this
1445 /// variable declaration.
1446 ///
1447 /// Every variable template is represented as a VarTemplateDecl and a
1448 /// VarDecl. The former contains template properties (such as
1449 /// the template parameter lists) while the latter contains the
1450 /// actual description of the template's
1451 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1452 /// VarDecl that from a VarTemplateDecl, while
1453 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1454 /// a VarDecl.
1455 VarTemplateDecl *getDescribedVarTemplate() const;
1456
1457 void setDescribedVarTemplate(VarTemplateDecl *Template);
1458
1459 // Implement isa/cast/dyncast/etc.
1460 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1461 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1462};
1463
1464class ImplicitParamDecl : public VarDecl {
1465 void anchor() override;
1466
1467public:
1468 /// Defines the kind of the implicit parameter: is this an implicit parameter
1469 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1470 /// context or something else.
1471 enum ImplicitParamKind : unsigned {
1472 /// Parameter for Objective-C 'self' argument
1473 ObjCSelf,
1474
1475 /// Parameter for Objective-C '_cmd' argument
1476 ObjCCmd,
1477
1478 /// Parameter for C++ 'this' argument
1479 CXXThis,
1480
1481 /// Parameter for C++ virtual table pointers
1482 CXXVTT,
1483
1484 /// Parameter for captured context
1485 CapturedContext,
1486
1487 /// Other implicit parameter
1488 Other,
1489 };
1490
1491 /// Create implicit parameter.
1492 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1493 SourceLocation IdLoc, IdentifierInfo *Id,
1494 QualType T, ImplicitParamKind ParamKind);
1495 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1496 ImplicitParamKind ParamKind);
1497
1498 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1499
1500 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1501 IdentifierInfo *Id, QualType Type,
1502 ImplicitParamKind ParamKind)
1503 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1504 /*TInfo=*/nullptr, SC_None) {
1505 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1506 setImplicit();
1507 }
1508
1509 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1510 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1511 SourceLocation(), /*Id=*/nullptr, Type,
1512 /*TInfo=*/nullptr, SC_None) {
1513 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1514 setImplicit();
1515 }
1516
1517 /// Returns the implicit parameter kind.
1518 ImplicitParamKind getParameterKind() const {
1519 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1520 }
1521
1522 // Implement isa/cast/dyncast/etc.
1523 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1524 static bool classofKind(Kind K) { return K == ImplicitParam; }
1525};
1526
1527/// Represents a parameter to a function.
1528class ParmVarDecl : public VarDecl {
1529public:
1530 enum { MaxFunctionScopeDepth = 255 };
1531 enum { MaxFunctionScopeIndex = 255 };
1532
1533protected:
1534 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1535 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1536 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1537 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1538 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1538, __extension__ __PRETTY_FUNCTION__))
;
1539 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1539, __extension__ __PRETTY_FUNCTION__))
;
1540 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1540, __extension__ __PRETTY_FUNCTION__))
;
1541 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1541, __extension__ __PRETTY_FUNCTION__))
;
1542 setDefaultArg(DefArg);
1543 }
1544
1545public:
1546 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1547 SourceLocation StartLoc,
1548 SourceLocation IdLoc, IdentifierInfo *Id,
1549 QualType T, TypeSourceInfo *TInfo,
1550 StorageClass S, Expr *DefArg);
1551
1552 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1553
1554 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1555
1556 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1557 ParmVarDeclBits.IsObjCMethodParam = true;
1558 setParameterIndex(parameterIndex);
1559 }
1560
1561 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1562 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1562, __extension__ __PRETTY_FUNCTION__))
;
1563
1564 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1565 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1566, __extension__ __PRETTY_FUNCTION__))
1566 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1566, __extension__ __PRETTY_FUNCTION__))
;
1567
1568 setParameterIndex(parameterIndex);
1569 }
1570
1571 bool isObjCMethodParameter() const {
1572 return ParmVarDeclBits.IsObjCMethodParam;
1573 }
1574
1575 unsigned getFunctionScopeDepth() const {
1576 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1577 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1578 }
1579
1580 /// Returns the index of this parameter in its prototype or method scope.
1581 unsigned getFunctionScopeIndex() const {
1582 return getParameterIndex();
1583 }
1584
1585 ObjCDeclQualifier getObjCDeclQualifier() const {
1586 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1587 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1588 }
1589 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1590 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1590, __extension__ __PRETTY_FUNCTION__))
;
1591 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1592 }
1593
1594 /// True if the value passed to this parameter must undergo
1595 /// K&R-style default argument promotion:
1596 ///
1597 /// C99 6.5.2.2.
1598 /// If the expression that denotes the called function has a type
1599 /// that does not include a prototype, the integer promotions are
1600 /// performed on each argument, and arguments that have type float
1601 /// are promoted to double.
1602 bool isKNRPromoted() const {
1603 return ParmVarDeclBits.IsKNRPromoted;
1604 }
1605 void setKNRPromoted(bool promoted) {
1606 ParmVarDeclBits.IsKNRPromoted = promoted;
1607 }
1608
1609 Expr *getDefaultArg();
1610 const Expr *getDefaultArg() const {
1611 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1612 }
1613
1614 void setDefaultArg(Expr *defarg);
1615
1616 /// \brief Retrieve the source range that covers the entire default
1617 /// argument.
1618 SourceRange getDefaultArgRange() const;
1619 void setUninstantiatedDefaultArg(Expr *arg);
1620 Expr *getUninstantiatedDefaultArg();
1621 const Expr *getUninstantiatedDefaultArg() const {
1622 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1623 }
1624
1625 /// Determines whether this parameter has a default argument,
1626 /// either parsed or not.
1627 bool hasDefaultArg() const;
1628
1629 /// Determines whether this parameter has a default argument that has not
1630 /// yet been parsed. This will occur during the processing of a C++ class
1631 /// whose member functions have default arguments, e.g.,
1632 /// @code
1633 /// class X {
1634 /// public:
1635 /// void f(int x = 17); // x has an unparsed default argument now
1636 /// }; // x has a regular default argument now
1637 /// @endcode
1638 bool hasUnparsedDefaultArg() const {
1639 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1640 }
1641
1642 bool hasUninstantiatedDefaultArg() const {
1643 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1644 }
1645
1646 /// Specify that this parameter has an unparsed default argument.
1647 /// The argument will be replaced with a real default argument via
1648 /// setDefaultArg when the class definition enclosing the function
1649 /// declaration that owns this default argument is completed.
1650 void setUnparsedDefaultArg() {
1651 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1652 }
1653
1654 bool hasInheritedDefaultArg() const {
1655 return ParmVarDeclBits.HasInheritedDefaultArg;
1656 }
1657
1658 void setHasInheritedDefaultArg(bool I = true) {
1659 ParmVarDeclBits.HasInheritedDefaultArg = I;
1660 }
1661
1662 QualType getOriginalType() const;
1663
1664 /// \brief Determine whether this parameter is actually a function
1665 /// parameter pack.
1666 bool isParameterPack() const;
1667
1668 /// Sets the function declaration that owns this
1669 /// ParmVarDecl. Since ParmVarDecls are often created before the
1670 /// FunctionDecls that own them, this routine is required to update
1671 /// the DeclContext appropriately.
1672 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1673
1674 // Implement isa/cast/dyncast/etc.
1675 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1676 static bool classofKind(Kind K) { return K == ParmVar; }
1677
1678private:
1679 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1680
1681 void setParameterIndex(unsigned parameterIndex) {
1682 if (parameterIndex >= ParameterIndexSentinel) {
1683 setParameterIndexLarge(parameterIndex);
1684 return;
1685 }
1686
1687 ParmVarDeclBits.ParameterIndex = parameterIndex;
1688 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 1688, __extension__ __PRETTY_FUNCTION__))
;
1689 }
1690 unsigned getParameterIndex() const {
1691 unsigned d = ParmVarDeclBits.ParameterIndex;
1692 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1693 }
1694
1695 void setParameterIndexLarge(unsigned parameterIndex);
1696 unsigned getParameterIndexLarge() const;
1697};
1698
1699/// Represents a function declaration or definition.
1700///
1701/// Since a given function can be declared several times in a program,
1702/// there may be several FunctionDecls that correspond to that
1703/// function. Only one of those FunctionDecls will be found when
1704/// traversing the list of declarations in the context of the
1705/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1706/// contains all of the information known about the function. Other,
1707/// previous declarations of the function are available via the
1708/// getPreviousDecl() chain.
1709class FunctionDecl : public DeclaratorDecl, public DeclContext,
1710 public Redeclarable<FunctionDecl> {
1711public:
1712 /// \brief The kind of templated function a FunctionDecl can be.
1713 enum TemplatedKind {
1714 TK_NonTemplate,
1715 TK_FunctionTemplate,
1716 TK_MemberSpecialization,
1717 TK_FunctionTemplateSpecialization,
1718 TK_DependentFunctionTemplateSpecialization
1719 };
1720
1721private:
1722 /// A new[]'d array of pointers to VarDecls for the formal
1723 /// parameters of this function. This is null if a prototype or if there are
1724 /// no formals.
1725 ParmVarDecl **ParamInfo = nullptr;
1726
1727 LazyDeclStmtPtr Body;
1728
1729 // FIXME: This can be packed into the bitfields in DeclContext.
1730 // NOTE: VC++ packs bitfields poorly if the types differ.
1731 unsigned SClass : 3;
1732 unsigned IsInline : 1;
1733 unsigned IsInlineSpecified : 1;
1734
1735protected:
1736 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1737 // CXXDeductionGuideDecl.
1738 unsigned IsExplicitSpecified : 1;
1739
1740private:
1741 unsigned IsVirtualAsWritten : 1;
1742 unsigned IsPure : 1;
1743 unsigned HasInheritedPrototype : 1;
1744 unsigned HasWrittenPrototype : 1;
1745 unsigned IsDeleted : 1;
1746 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1747
1748 /// This flag indicates whether this function is trivial for the purpose of
1749 /// calls. This is meaningful only when this function is a copy/move
1750 /// constructor or a destructor.
1751 unsigned IsTrivialForCall : 1;
1752
1753 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1754 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1755 unsigned HasImplicitReturnZero : 1;
1756 unsigned IsLateTemplateParsed : 1;
1757 unsigned IsConstexpr : 1;
1758 unsigned InstantiationIsPending : 1;
1759
1760 /// \brief Indicates if the function uses __try.
1761 unsigned UsesSEHTry : 1;
1762
1763 /// \brief Indicates if the function was a definition but its body was
1764 /// skipped.
1765 unsigned HasSkippedBody : 1;
1766
1767 /// Indicates if the function declaration will have a body, once we're done
1768 /// parsing it.
1769 unsigned WillHaveBody : 1;
1770
1771 /// Indicates that this function is a multiversioned function using attribute
1772 /// 'target'.
1773 unsigned IsMultiVersion : 1;
1774
1775protected:
1776 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1777 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1778 /// int as opposed to adding a single bit to FunctionDecl.
1779 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1780 /// deduction candidate' (is used during overload resolution).
1781 unsigned IsCopyDeductionCandidate : 1;
1782
1783private:
1784
1785 /// Store the ODRHash after first calculation.
1786 unsigned HasODRHash : 1;
1787 unsigned ODRHash;
1788
1789 /// \brief End part of this FunctionDecl's source range.
1790 ///
1791 /// We could compute the full range in getSourceRange(). However, when we're
1792 /// dealing with a function definition deserialized from a PCH/AST file,
1793 /// we can only compute the full range once the function body has been
1794 /// de-serialized, so it's far better to have the (sometimes-redundant)
1795 /// EndRangeLoc.
1796 SourceLocation EndRangeLoc;
1797
1798 /// \brief The template or declaration that this declaration
1799 /// describes or was instantiated from, respectively.
1800 ///
1801 /// For non-templates, this value will be NULL. For function
1802 /// declarations that describe a function template, this will be a
1803 /// pointer to a FunctionTemplateDecl. For member functions
1804 /// of class template specializations, this will be a MemberSpecializationInfo
1805 /// pointer containing information about the specialization.
1806 /// For function template specializations, this will be a
1807 /// FunctionTemplateSpecializationInfo, which contains information about
1808 /// the template being specialized and the template arguments involved in
1809 /// that specialization.
1810 llvm::PointerUnion4<FunctionTemplateDecl *,
1811 MemberSpecializationInfo *,
1812 FunctionTemplateSpecializationInfo *,
1813 DependentFunctionTemplateSpecializationInfo *>
1814 TemplateOrSpecialization;
1815
1816 /// Provides source/type location info for the declaration name embedded in
1817 /// the DeclaratorDecl base class.
1818 DeclarationNameLoc DNLoc;
1819
1820 /// \brief Specify that this function declaration is actually a function
1821 /// template specialization.
1822 ///
1823 /// \param C the ASTContext.
1824 ///
1825 /// \param Template the function template that this function template
1826 /// specialization specializes.
1827 ///
1828 /// \param TemplateArgs the template arguments that produced this
1829 /// function template specialization from the template.
1830 ///
1831 /// \param InsertPos If non-NULL, the position in the function template
1832 /// specialization set where the function template specialization data will
1833 /// be inserted.
1834 ///
1835 /// \param TSK the kind of template specialization this is.
1836 ///
1837 /// \param TemplateArgsAsWritten location info of template arguments.
1838 ///
1839 /// \param PointOfInstantiation point at which the function template
1840 /// specialization was first instantiated.
1841 void setFunctionTemplateSpecialization(ASTContext &C,
1842 FunctionTemplateDecl *Template,
1843 const TemplateArgumentList *TemplateArgs,
1844 void *InsertPos,
1845 TemplateSpecializationKind TSK,
1846 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1847 SourceLocation PointOfInstantiation);
1848
1849 /// \brief Specify that this record is an instantiation of the
1850 /// member function FD.
1851 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1852 TemplateSpecializationKind TSK);
1853
1854 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1855
1856protected:
1857 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1858 const DeclarationNameInfo &NameInfo, QualType T,
1859 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1860 bool isConstexprSpecified)
1861 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1862 StartLoc),
1863 DeclContext(DK), redeclarable_base(C), SClass(S),
1864 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1865 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1866 HasInheritedPrototype(false), HasWrittenPrototype(true),
1867 IsDeleted(false), IsTrivial(false), IsTrivialForCall(false),
1868 IsDefaulted(false),
1869 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1870 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1871 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1872 WillHaveBody(false), IsMultiVersion(false),
1873 IsCopyDeductionCandidate(false), HasODRHash(false), ODRHash(0),
1874 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1875
1876 using redeclarable_base = Redeclarable<FunctionDecl>;
1877
1878 FunctionDecl *getNextRedeclarationImpl() override {
1879 return getNextRedeclaration();
1880 }
1881
1882 FunctionDecl *getPreviousDeclImpl() override {
1883 return getPreviousDecl();
1884 }
1885
1886 FunctionDecl *getMostRecentDeclImpl() override {
1887 return getMostRecentDecl();
1888 }
1889
1890public:
1891 friend class ASTDeclReader;
1892 friend class ASTDeclWriter;
1893
1894 using redecl_range = redeclarable_base::redecl_range;
1895 using redecl_iterator = redeclarable_base::redecl_iterator;
1896
1897 using redeclarable_base::redecls_begin;
1898 using redeclarable_base::redecls_end;
1899 using redeclarable_base::redecls;
1900 using redeclarable_base::getPreviousDecl;
1901 using redeclarable_base::getMostRecentDecl;
1902 using redeclarable_base::isFirstDecl;
1903
1904 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1905 SourceLocation StartLoc, SourceLocation NLoc,
1906 DeclarationName N, QualType T,
1907 TypeSourceInfo *TInfo,
1908 StorageClass SC,
1909 bool isInlineSpecified = false,
1910 bool hasWrittenPrototype = true,
1911 bool isConstexprSpecified = false) {
1912 DeclarationNameInfo NameInfo(N, NLoc);
1913 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1914 SC,
1915 isInlineSpecified, hasWrittenPrototype,
1916 isConstexprSpecified);
1917 }
1918
1919 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1920 SourceLocation StartLoc,
1921 const DeclarationNameInfo &NameInfo,
1922 QualType T, TypeSourceInfo *TInfo,
1923 StorageClass SC,
1924 bool isInlineSpecified,
1925 bool hasWrittenPrototype,
1926 bool isConstexprSpecified = false);
1927
1928 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1929
1930 DeclarationNameInfo getNameInfo() const {
1931 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1932 }
1933
1934 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1935 bool Qualified) const override;
1936
1937 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1938
1939 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1940
1941 // Function definitions.
1942 //
1943 // A function declaration may be:
1944 // - a non defining declaration,
1945 // - a definition. A function may be defined because:
1946 // - it has a body, or will have it in the case of late parsing.
1947 // - it has an uninstantiated body. The body does not exist because the
1948 // function is not used yet, but the declaration is considered a
1949 // definition and does not allow other definition of this function.
1950 // - it does not have a user specified body, but it does not allow
1951 // redefinition, because it is deleted/defaulted or is defined through
1952 // some other mechanism (alias, ifunc).
1953
1954 /// Returns true if the function has a body.
1955 ///
1956 /// The function body might be in any of the (re-)declarations of this
1957 /// function. The variant that accepts a FunctionDecl pointer will set that
1958 /// function declaration to the actual declaration containing the body (if
1959 /// there is one).
1960 bool hasBody(const FunctionDecl *&Definition) const;
1961
1962 bool hasBody() const override {
1963 const FunctionDecl* Definition;
1964 return hasBody(Definition);
1965 }
1966
1967 /// Returns whether the function has a trivial body that does not require any
1968 /// specific codegen.
1969 bool hasTrivialBody() const;
1970
1971 /// Returns true if the function has a definition that does not need to be
1972 /// instantiated.
1973 ///
1974 /// The variant that accepts a FunctionDecl pointer will set that function
1975 /// declaration to the declaration that is a definition (if there is one).
1976 bool isDefined(const FunctionDecl *&Definition) const;
1977
1978 virtual bool isDefined() const {
1979 const FunctionDecl* Definition;
1980 return isDefined(Definition);
1981 }
1982
1983 /// \brief Get the definition for this declaration.
1984 FunctionDecl *getDefinition() {
1985 const FunctionDecl *Definition;
1986 if (isDefined(Definition))
1987 return const_cast<FunctionDecl *>(Definition);
1988 return nullptr;
1989 }
1990 const FunctionDecl *getDefinition() const {
1991 return const_cast<FunctionDecl *>(this)->getDefinition();
1992 }
1993
1994 /// Retrieve the body (definition) of the function. The function body might be
1995 /// in any of the (re-)declarations of this function. The variant that accepts
1996 /// a FunctionDecl pointer will set that function declaration to the actual
1997 /// declaration containing the body (if there is one).
1998 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1999 /// unnecessary AST de-serialization of the body.
2000 Stmt *getBody(const FunctionDecl *&Definition) const;
2001
2002 Stmt *getBody() const override {
2003 const FunctionDecl* Definition;
2004 return getBody(Definition);
2005 }
2006
2007 /// Returns whether this specific declaration of the function is also a
2008 /// definition that does not contain uninstantiated body.
2009 ///
2010 /// This does not determine whether the function has been defined (e.g., in a
2011 /// previous definition); for that information, use isDefined.
2012 bool isThisDeclarationADefinition() const {
2013 return IsDeleted || IsDefaulted || Body || HasSkippedBody ||
2014 IsLateTemplateParsed || WillHaveBody || hasDefiningAttr();
2015 }
2016
2017 /// Returns whether this specific declaration of the function has a body.
2018 bool doesThisDeclarationHaveABody() const {
2019 return Body || IsLateTemplateParsed;
2020 }
2021
2022 void setBody(Stmt *B);
2023 void setLazyBody(uint64_t Offset) { Body = Offset; }
2024
2025 /// Whether this function is variadic.
2026 bool isVariadic() const;
2027
2028 /// Whether this function is marked as virtual explicitly.
2029 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
2030 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
2031
2032 /// Whether this virtual function is pure, i.e. makes the containing class
2033 /// abstract.
2034 bool isPure() const { return IsPure; }
2035 void setPure(bool P = true);
2036
2037 /// Whether this templated function will be late parsed.
2038 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
2039 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
2040
2041 /// Whether this function is "trivial" in some specialized C++ senses.
2042 /// Can only be true for default constructors, copy constructors,
2043 /// copy assignment operators, and destructors. Not meaningful until
2044 /// the class has been fully built by Sema.
2045 bool isTrivial() const { return IsTrivial; }
2046 void setTrivial(bool IT) { IsTrivial = IT; }
2047
2048 bool isTrivialForCall() const { return IsTrivialForCall; }
2049 void setTrivialForCall(bool IT) { IsTrivialForCall = IT; }
2050
2051 /// Whether this function is defaulted per C++0x. Only valid for
2052 /// special member functions.
2053 bool isDefaulted() const { return IsDefaulted; }
2054 void setDefaulted(bool D = true) { IsDefaulted = D; }
2055
2056 /// Whether this function is explicitly defaulted per C++0x. Only valid
2057 /// for special member functions.
2058 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2059 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2060
2061 /// Whether falling off this function implicitly returns null/zero.
2062 /// If a more specific implicit return value is required, front-ends
2063 /// should synthesize the appropriate return statements.
2064 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2065 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2066
2067 /// \brief Whether this function has a prototype, either because one
2068 /// was explicitly written or because it was "inherited" by merging
2069 /// a declaration without a prototype with a declaration that has a
2070 /// prototype.
2071 bool hasPrototype() const {
2072 return HasWrittenPrototype || HasInheritedPrototype;
2073 }
2074
2075 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2076
2077 /// \brief Whether this function inherited its prototype from a
2078 /// previous declaration.
2079 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2080 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2081
2082 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2083 bool isConstexpr() const { return IsConstexpr; }
2084 void setConstexpr(bool IC) { IsConstexpr = IC; }
2085
2086 /// \brief Whether the instantiation of this function is pending.
2087 /// This bit is set when the decision to instantiate this function is made
2088 /// and unset if and when the function body is created. That leaves out
2089 /// cases where instantiation did not happen because the template definition
2090 /// was not seen in this TU. This bit remains set in those cases, under the
2091 /// assumption that the instantiation will happen in some other TU.
2092 bool instantiationIsPending() const { return InstantiationIsPending; }
2093 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2094
2095 /// \brief Indicates the function uses __try.
2096 bool usesSEHTry() const { return UsesSEHTry; }
2097 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2098
2099 /// \brief Whether this function has been deleted.
2100 ///
2101 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2102 /// acts like a normal function, except that it cannot actually be
2103 /// called or have its address taken. Deleted functions are
2104 /// typically used in C++ overload resolution to attract arguments
2105 /// whose type or lvalue/rvalue-ness would permit the use of a
2106 /// different overload that would behave incorrectly. For example,
2107 /// one might use deleted functions to ban implicit conversion from
2108 /// a floating-point number to an Integer type:
2109 ///
2110 /// @code
2111 /// struct Integer {
2112 /// Integer(long); // construct from a long
2113 /// Integer(double) = delete; // no construction from float or double
2114 /// Integer(long double) = delete; // no construction from long double
2115 /// };
2116 /// @endcode
2117 // If a function is deleted, its first declaration must be.
2118 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2119 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2120 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2121
2122 /// \brief Determines whether this function is "main", which is the
2123 /// entry point into an executable program.
2124 bool isMain() const;
2125
2126 /// \brief Determines whether this function is a MSVCRT user defined entry
2127 /// point.
2128 bool isMSVCRTEntryPoint() const;
2129
2130 /// \brief Determines whether this operator new or delete is one
2131 /// of the reserved global placement operators:
2132 /// void *operator new(size_t, void *);
2133 /// void *operator new[](size_t, void *);
2134 /// void operator delete(void *, void *);
2135 /// void operator delete[](void *, void *);
2136 /// These functions have special behavior under [new.delete.placement]:
2137 /// These functions are reserved, a C++ program may not define
2138 /// functions that displace the versions in the Standard C++ library.
2139 /// The provisions of [basic.stc.dynamic] do not apply to these
2140 /// reserved placement forms of operator new and operator delete.
2141 ///
2142 /// This function must be an allocation or deallocation function.
2143 bool isReservedGlobalPlacementOperator() const;
2144
2145 /// \brief Determines whether this function is one of the replaceable
2146 /// global allocation functions:
2147 /// void *operator new(size_t);
2148 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2149 /// void *operator new[](size_t);
2150 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2151 /// void operator delete(void *) noexcept;
2152 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2153 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2154 /// void operator delete[](void *) noexcept;
2155 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2156 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2157 /// These functions have special behavior under C++1y [expr.new]:
2158 /// An implementation is allowed to omit a call to a replaceable global
2159 /// allocation function. [...]
2160 ///
2161 /// If this function is an aligned allocation/deallocation function, return
2162 /// true through IsAligned.
2163 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2164
2165 /// \brief Determine whether this is a destroying operator delete.
2166 bool isDestroyingOperatorDelete() const;
2167
2168 /// Compute the language linkage.
2169 LanguageLinkage getLanguageLinkage() const;
2170
2171 /// \brief Determines whether this function is a function with
2172 /// external, C linkage.
2173 bool isExternC() const;
2174
2175 /// \brief Determines whether this function's context is, or is nested within,
2176 /// a C++ extern "C" linkage spec.
2177 bool isInExternCContext() const;
2178
2179 /// \brief Determines whether this function's context is, or is nested within,
2180 /// a C++ extern "C++" linkage spec.
2181 bool isInExternCXXContext() const;
2182
2183 /// \brief Determines whether this is a global function.
2184 bool isGlobal() const;
2185
2186 /// \brief Determines whether this function is known to be 'noreturn', through
2187 /// an attribute on its declaration or its type.
2188 bool isNoReturn() const;
2189
2190 /// \brief True if the function was a definition but its body was skipped.
2191 bool hasSkippedBody() const { return HasSkippedBody; }
2192 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2193
2194 /// True if this function will eventually have a body, once it's fully parsed.
2195 bool willHaveBody() const { return WillHaveBody; }
2196 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2197
2198 /// True if this function is considered a multiversioned function.
2199 bool isMultiVersion() const { return getCanonicalDecl()->IsMultiVersion; }
2200
2201 /// Sets the multiversion state for this declaration and all of its
2202 /// redeclarations.
2203 void setIsMultiVersion(bool V = true) {
2204 getCanonicalDecl()->IsMultiVersion = V;
2205 }
2206
2207 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2208
2209 FunctionDecl *getCanonicalDecl() override;
2210 const FunctionDecl *getCanonicalDecl() const {
2211 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2212 }
2213
2214 unsigned getBuiltinID() const;
2215
2216 // ArrayRef interface to parameters.
2217 ArrayRef<ParmVarDecl *> parameters() const {
2218 return {ParamInfo, getNumParams()};
2219 }
2220 MutableArrayRef<ParmVarDecl *> parameters() {
2221 return {ParamInfo, getNumParams()};
2222 }
2223
2224 // Iterator access to formal parameters.
2225 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2226 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2227
2228 bool param_empty() const { return parameters().empty(); }
2229 param_iterator param_begin() { return parameters().begin(); }
2230 param_iterator param_end() { return parameters().end(); }
2231 param_const_iterator param_begin() const { return parameters().begin(); }
2232 param_const_iterator param_end() const { return parameters().end(); }
2233 size_t param_size() const { return parameters().size(); }
2234
2235 /// Return the number of parameters this function must have based on its
2236 /// FunctionType. This is the length of the ParamInfo array after it has been
2237 /// created.
2238 unsigned getNumParams() const;
2239
2240 const ParmVarDecl *getParamDecl(unsigned i) const {
2241 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2241, __extension__ __PRETTY_FUNCTION__))
;
31
Within the expansion of the macro 'assert':
a
Assuming the condition is true
2242 return ParamInfo[i];
2243 }
2244 ParmVarDecl *getParamDecl(unsigned i) {
2245 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2245, __extension__ __PRETTY_FUNCTION__))
;
2246 return ParamInfo[i];
2247 }
2248 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2249 setParams(getASTContext(), NewParamInfo);
2250 }
2251
2252 /// Returns the minimum number of arguments needed to call this function. This
2253 /// may be fewer than the number of function parameters, if some of the
2254 /// parameters have default arguments (in C++).
2255 unsigned getMinRequiredArguments() const;
2256
2257 QualType getReturnType() const {
2258 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2258, __extension__ __PRETTY_FUNCTION__))
;
2259 return getType()->getAs<FunctionType>()->getReturnType();
2260 }
2261
2262 /// \brief Attempt to compute an informative source range covering the
2263 /// function return type. This may omit qualifiers and other information with
2264 /// limited representation in the AST.
2265 SourceRange getReturnTypeSourceRange() const;
2266
2267 /// \brief Attempt to compute an informative source range covering the
2268 /// function exception specification, if any.
2269 SourceRange getExceptionSpecSourceRange() const;
2270
2271 /// \brief Determine the type of an expression that calls this function.
2272 QualType getCallResultType() const {
2273 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2273, __extension__ __PRETTY_FUNCTION__))
;
2274 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2275 }
2276
2277 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2278 /// function, or its return type declaration.
2279 const Attr *getUnusedResultAttr() const;
2280
2281 /// \brief Returns true if this function or its return type has the
2282 /// warn_unused_result attribute.
2283 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2284
2285 /// \brief Returns the storage class as written in the source. For the
2286 /// computed linkage of symbol, see getLinkage.
2287 StorageClass getStorageClass() const { return StorageClass(SClass); }
2288
2289 /// \brief Determine whether the "inline" keyword was specified for this
2290 /// function.
2291 bool isInlineSpecified() const { return IsInlineSpecified; }
2292
2293 /// Set whether the "inline" keyword was specified for this function.
2294 void setInlineSpecified(bool I) {
2295 IsInlineSpecified = I;
2296 IsInline = I;
2297 }
2298
2299 /// Flag that this function is implicitly inline.
2300 void setImplicitlyInline() {
2301 IsInline = true;
2302 }
2303
2304 /// \brief Determine whether this function should be inlined, because it is
2305 /// either marked "inline" or "constexpr" or is a member function of a class
2306 /// that was defined in the class body.
2307 bool isInlined() const { return IsInline; }
2308
2309 bool isInlineDefinitionExternallyVisible() const;
2310
2311 bool isMSExternInline() const;
2312
2313 bool doesDeclarationForceExternallyVisibleDefinition() const;
2314
2315 /// Whether this function declaration represents an C++ overloaded
2316 /// operator, e.g., "operator+".
2317 bool isOverloadedOperator() const {
2318 return getOverloadedOperator() != OO_None;
2319 }
2320
2321 OverloadedOperatorKind getOverloadedOperator() const;
2322
2323 const IdentifierInfo *getLiteralIdentifier() const;
2324
2325 /// \brief If this function is an instantiation of a member function
2326 /// of a class template specialization, retrieves the function from
2327 /// which it was instantiated.
2328 ///
2329 /// This routine will return non-NULL for (non-templated) member
2330 /// functions of class templates and for instantiations of function
2331 /// templates. For example, given:
2332 ///
2333 /// \code
2334 /// template<typename T>
2335 /// struct X {
2336 /// void f(T);
2337 /// };
2338 /// \endcode
2339 ///
2340 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2341 /// whose parent is the class template specialization X<int>. For
2342 /// this declaration, getInstantiatedFromFunction() will return
2343 /// the FunctionDecl X<T>::A. When a complete definition of
2344 /// X<int>::A is required, it will be instantiated from the
2345 /// declaration returned by getInstantiatedFromMemberFunction().
2346 FunctionDecl *getInstantiatedFromMemberFunction() const;
2347
2348 /// \brief What kind of templated function this is.
2349 TemplatedKind getTemplatedKind() const;
2350
2351 /// \brief If this function is an instantiation of a member function of a
2352 /// class template specialization, retrieves the member specialization
2353 /// information.
2354 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2355
2356 /// \brief Specify that this record is an instantiation of the
2357 /// member function FD.
2358 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2359 TemplateSpecializationKind TSK) {
2360 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2361 }
2362
2363 /// \brief Retrieves the function template that is described by this
2364 /// function declaration.
2365 ///
2366 /// Every function template is represented as a FunctionTemplateDecl
2367 /// and a FunctionDecl (or something derived from FunctionDecl). The
2368 /// former contains template properties (such as the template
2369 /// parameter lists) while the latter contains the actual
2370 /// description of the template's
2371 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2372 /// FunctionDecl that describes the function template,
2373 /// getDescribedFunctionTemplate() retrieves the
2374 /// FunctionTemplateDecl from a FunctionDecl.
2375 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2376
2377 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2378
2379 /// \brief Determine whether this function is a function template
2380 /// specialization.
2381 bool isFunctionTemplateSpecialization() const {
2382 return getPrimaryTemplate() != nullptr;
2383 }
2384
2385 /// \brief Retrieve the class scope template pattern that this function
2386 /// template specialization is instantiated from.
2387 FunctionDecl *getClassScopeSpecializationPattern() const;
2388
2389 /// \brief If this function is actually a function template specialization,
2390 /// retrieve information about this function template specialization.
2391 /// Otherwise, returns NULL.
2392 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2393
2394 /// \brief Determines whether this function is a function template
2395 /// specialization or a member of a class template specialization that can
2396 /// be implicitly instantiated.
2397 bool isImplicitlyInstantiable() const;
2398
2399 /// \brief Determines if the given function was instantiated from a
2400 /// function template.
2401 bool isTemplateInstantiation() const;
2402
2403 /// \brief Retrieve the function declaration from which this function could
2404 /// be instantiated, if it is an instantiation (rather than a non-template
2405 /// or a specialization, for example).
2406 FunctionDecl *getTemplateInstantiationPattern() const;
2407
2408 /// \brief Retrieve the primary template that this function template
2409 /// specialization either specializes or was instantiated from.
2410 ///
2411 /// If this function declaration is not a function template specialization,
2412 /// returns NULL.
2413 FunctionTemplateDecl *getPrimaryTemplate() const;
2414
2415 /// \brief Retrieve the template arguments used to produce this function
2416 /// template specialization from the primary template.
2417 ///
2418 /// If this function declaration is not a function template specialization,
2419 /// returns NULL.
2420 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2421
2422 /// \brief Retrieve the template argument list as written in the sources,
2423 /// if any.
2424 ///
2425 /// If this function declaration is not a function template specialization
2426 /// or if it had no explicit template argument list, returns NULL.
2427 /// Note that it an explicit template argument list may be written empty,
2428 /// e.g., template<> void foo<>(char* s);
2429 const ASTTemplateArgumentListInfo*
2430 getTemplateSpecializationArgsAsWritten() const;
2431
2432 /// \brief Specify that this function declaration is actually a function
2433 /// template specialization.
2434 ///
2435 /// \param Template the function template that this function template
2436 /// specialization specializes.
2437 ///
2438 /// \param TemplateArgs the template arguments that produced this
2439 /// function template specialization from the template.
2440 ///
2441 /// \param InsertPos If non-NULL, the position in the function template
2442 /// specialization set where the function template specialization data will
2443 /// be inserted.
2444 ///
2445 /// \param TSK the kind of template specialization this is.
2446 ///
2447 /// \param TemplateArgsAsWritten location info of template arguments.
2448 ///
2449 /// \param PointOfInstantiation point at which the function template
2450 /// specialization was first instantiated.
2451 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2452 const TemplateArgumentList *TemplateArgs,
2453 void *InsertPos,
2454 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2455 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2456 SourceLocation PointOfInstantiation = SourceLocation()) {
2457 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2458 InsertPos, TSK, TemplateArgsAsWritten,
2459 PointOfInstantiation);
2460 }
2461
2462 /// \brief Specifies that this function declaration is actually a
2463 /// dependent function template specialization.
2464 void setDependentTemplateSpecialization(ASTContext &Context,
2465 const UnresolvedSetImpl &Templates,
2466 const TemplateArgumentListInfo &TemplateArgs);
2467
2468 DependentFunctionTemplateSpecializationInfo *
2469 getDependentSpecializationInfo() const;
2470
2471 /// \brief Determine what kind of template instantiation this function
2472 /// represents.
2473 TemplateSpecializationKind getTemplateSpecializationKind() const;
2474
2475 /// \brief Determine what kind of template instantiation this function
2476 /// represents.
2477 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2478 SourceLocation PointOfInstantiation = SourceLocation());
2479
2480 /// \brief Retrieve the (first) point of instantiation of a function template
2481 /// specialization or a member of a class template specialization.
2482 ///
2483 /// \returns the first point of instantiation, if this function was
2484 /// instantiated from a template; otherwise, returns an invalid source
2485 /// location.
2486 SourceLocation getPointOfInstantiation() const;
2487
2488 /// \brief Determine whether this is or was instantiated from an out-of-line
2489 /// definition of a member function.
2490 bool isOutOfLine() const override;
2491
2492 /// \brief Identify a memory copying or setting function.
2493 /// If the given function is a memory copy or setting function, returns
2494 /// the corresponding Builtin ID. If the function is not a memory function,
2495 /// returns 0.
2496 unsigned getMemoryFunctionKind() const;
2497
2498 /// \brief Returns ODRHash of the function. This value is calculated and
2499 /// stored on first call, then the stored value returned on the other calls.
2500 unsigned getODRHash();
2501
2502 // Implement isa/cast/dyncast/etc.
2503 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2504 static bool classofKind(Kind K) {
2505 return K >= firstFunction && K <= lastFunction;
2506 }
2507 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2508 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2509 }
2510 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2511 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2512 }
2513};
2514
2515/// Represents a member of a struct/union/class.
2516class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2517 unsigned BitField : 1;
2518 unsigned Mutable : 1;
2519 mutable unsigned CachedFieldIndex : 30;
2520
2521 /// The kinds of value we can store in InitializerOrBitWidth.
2522 ///
2523 /// Note that this is compatible with InClassInitStyle except for
2524 /// ISK_CapturedVLAType.
2525 enum InitStorageKind {
2526 /// If the pointer is null, there's nothing special. Otherwise,
2527 /// this is a bitfield and the pointer is the Expr* storing the
2528 /// bit-width.
2529 ISK_NoInit = (unsigned) ICIS_NoInit,
2530
2531 /// The pointer is an (optional due to delayed parsing) Expr*
2532 /// holding the copy-initializer.
2533 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2534
2535 /// The pointer is an (optional due to delayed parsing) Expr*
2536 /// holding the list-initializer.
2537 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2538
2539 /// The pointer is a VariableArrayType* that's been captured;
2540 /// the enclosing context is a lambda or captured statement.
2541 ISK_CapturedVLAType,
2542 };
2543
2544 /// If this is a bitfield with a default member initializer, this
2545 /// structure is used to represent the two expressions.
2546 struct InitAndBitWidth {
2547 Expr *Init;
2548 Expr *BitWidth;
2549 };
2550
2551 /// \brief Storage for either the bit-width, the in-class initializer, or
2552 /// both (via InitAndBitWidth), or the captured variable length array bound.
2553 ///
2554 /// If the storage kind is ISK_InClassCopyInit or
2555 /// ISK_InClassListInit, but the initializer is null, then this
2556 /// field has an in-class initializer that has not yet been parsed
2557 /// and attached.
2558 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2559 // overwhelmingly common case that we have none of these things.
2560 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2561
2562protected:
2563 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2564 SourceLocation IdLoc, IdentifierInfo *Id,
2565 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2566 InClassInitStyle InitStyle)
2567 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2568 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2569 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2570 if (BW)
2571 setBitWidth(BW);
2572 }
2573
2574public:
2575 friend class ASTDeclReader;
2576 friend class ASTDeclWriter;
2577
2578 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2579 SourceLocation StartLoc, SourceLocation IdLoc,
2580 IdentifierInfo *Id, QualType T,
2581 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2582 InClassInitStyle InitStyle);
2583
2584 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2585
2586 /// Returns the index of this field within its record,
2587 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2588 unsigned getFieldIndex() const;
2589
2590 /// Determines whether this field is mutable (C++ only).
2591 bool isMutable() const { return Mutable; }
2592
2593 /// Determines whether this field is a bitfield.
2594 bool isBitField() const { return BitField; }
2595
2596 /// Determines whether this is an unnamed bitfield.
2597 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2598
2599 /// Determines whether this field is a
2600 /// representative for an anonymous struct or union. Such fields are
2601 /// unnamed and are implicitly generated by the implementation to
2602 /// store the data for the anonymous union or struct.
2603 bool isAnonymousStructOrUnion() const;
2604
2605 Expr *getBitWidth() const {
2606 if (!BitField)
2607 return nullptr;
2608 void *Ptr = InitStorage.getPointer();
2609 if (getInClassInitStyle())
2610 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2611 return static_cast<Expr*>(Ptr);
2612 }
2613
2614 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2615
2616 /// Set the bit-field width for this member.
2617 // Note: used by some clients (i.e., do not remove it).
2618 void setBitWidth(Expr *Width) {
2619 assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2620, __extension__ __PRETTY_FUNCTION__))
2620 "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2620, __extension__ __PRETTY_FUNCTION__))
;
2621 assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified"
) ? void (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2621, __extension__ __PRETTY_FUNCTION__))
;
2622 InitStorage.setPointer(
2623 InitStorage.getInt()
2624 ? new (getASTContext())
2625 InitAndBitWidth{getInClassInitializer(), Width}
2626 : static_cast<void*>(Width));
2627 BitField = true;
2628 }
2629
2630 /// Remove the bit-field width from this member.
2631 // Note: used by some clients (i.e., do not remove it).
2632 void removeBitWidth() {
2633 assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove"
) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2633, __extension__ __PRETTY_FUNCTION__))
;
2634 InitStorage.setPointer(getInClassInitializer());
2635 BitField = false;
2636 }
2637
2638 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2639 /// at all and instead act as a separator between contiguous runs of other
2640 /// bit-fields.
2641 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2642
2643 /// Get the kind of (C++11) default member initializer that this field has.
2644 InClassInitStyle getInClassInitStyle() const {
2645 InitStorageKind storageKind = InitStorage.getInt();
2646 return (storageKind == ISK_CapturedVLAType
2647 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2648 }
2649
2650 /// Determine whether this member has a C++11 default member initializer.
2651 bool hasInClassInitializer() const {
2652 return getInClassInitStyle() != ICIS_NoInit;
2653 }
2654
2655 /// Get the C++11 default member initializer for this member, or null if one
2656 /// has not been set. If a valid declaration has a default member initializer,
2657 /// but this returns null, then we have not parsed and attached it yet.
2658 Expr *getInClassInitializer() const {
2659 if (!hasInClassInitializer())
2660 return nullptr;
2661 void *Ptr = InitStorage.getPointer();
2662 if (BitField)
2663 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2664 return static_cast<Expr*>(Ptr);
2665 }
2666
2667 /// Set the C++11 in-class initializer for this member.
2668 void setInClassInitializer(Expr *Init) {
2669 assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() &&
!getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2669, __extension__ __PRETTY_FUNCTION__))
;
2670 if (BitField)
2671 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2672 else
2673 InitStorage.setPointer(Init);
2674 }
2675
2676 /// Remove the C++11 in-class initializer from this member.
2677 void removeInClassInitializer() {
2678 assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() &&
"no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2678, __extension__ __PRETTY_FUNCTION__))
;
2679 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2680 }
2681
2682 /// \brief Determine whether this member captures the variable length array
2683 /// type.
2684 bool hasCapturedVLAType() const {
2685 return InitStorage.getInt() == ISK_CapturedVLAType;
2686 }
2687
2688 /// \brief Get the captured variable length array type.
2689 const VariableArrayType *getCapturedVLAType() const {
2690 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2691 InitStorage.getPointer())
2692 : nullptr;
2693 }
2694
2695 /// \brief Set the captured variable length array type for this field.
2696 void setCapturedVLAType(const VariableArrayType *VLAType);
2697
2698 /// Returns the parent of this field declaration, which
2699 /// is the struct in which this field is defined.
2700 const RecordDecl *getParent() const {
2701 return cast<RecordDecl>(getDeclContext());
2702 }
2703
2704 RecordDecl *getParent() {
2705 return cast<RecordDecl>(getDeclContext());
2706 }
2707
2708 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2709
2710 /// Retrieves the canonical declaration of this field.
2711 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2712 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2713
2714 // Implement isa/cast/dyncast/etc.
2715 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2716 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2717};
2718
2719/// An instance of this object exists for each enum constant
2720/// that is defined. For example, in "enum X {a,b}", each of a/b are
2721/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2722/// TagType for the X EnumDecl.
2723class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2724 Stmt *Init; // an integer constant expression
2725 llvm::APSInt Val; // The value.
2726
2727protected:
2728 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2729 IdentifierInfo *Id, QualType T, Expr *E,
2730 const llvm::APSInt &V)
2731 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2732
2733public:
2734 friend class StmtIteratorBase;
2735
2736 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2737 SourceLocation L, IdentifierInfo *Id,
2738 QualType T, Expr *E,
2739 const llvm::APSInt &V);
2740 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2741
2742 const Expr *getInitExpr() const { return (const Expr*) Init; }
2743 Expr *getInitExpr() { return (Expr*) Init; }
2744 const llvm::APSInt &getInitVal() const { return Val; }
2745
2746 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2747 void setInitVal(const llvm::APSInt &V) { Val = V; }
2748
2749 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2750
2751 /// Retrieves the canonical declaration of this enumerator.
2752 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2753 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2754
2755 // Implement isa/cast/dyncast/etc.
2756 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2757 static bool classofKind(Kind K) { return K == EnumConstant; }
2758};
2759
2760/// Represents a field injected from an anonymous union/struct into the parent
2761/// scope. These are always implicit.
2762class IndirectFieldDecl : public ValueDecl,
2763 public Mergeable<IndirectFieldDecl> {
2764 NamedDecl **Chaining;
2765 unsigned ChainingSize;
2766
2767 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2768 DeclarationName N, QualType T,
2769 MutableArrayRef<NamedDecl *> CH);
2770
2771 void anchor() override;
2772
2773public:
2774 friend class ASTDeclReader;
2775
2776 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2777 SourceLocation L, IdentifierInfo *Id,
2778 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2779
2780 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2781
2782 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2783
2784 ArrayRef<NamedDecl *> chain() const {
2785 return llvm::makeArrayRef(Chaining, ChainingSize);
2786 }
2787 chain_iterator chain_begin() const { return chain().begin(); }
2788 chain_iterator chain_end() const { return chain().end(); }
2789
2790 unsigned getChainingSize() const { return ChainingSize; }
2791
2792 FieldDecl *getAnonField() const {
2793 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2793, __extension__ __PRETTY_FUNCTION__))
;
2794 return cast<FieldDecl>(chain().back());
2795 }
2796
2797 VarDecl *getVarDecl() const {
2798 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 2798, __extension__ __PRETTY_FUNCTION__))
;
2799 return dyn_cast<VarDecl>(chain().front());
2800 }
2801
2802 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2803 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2804
2805 // Implement isa/cast/dyncast/etc.
2806 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2807 static bool classofKind(Kind K) { return K == IndirectField; }
2808};
2809
2810/// Represents a declaration of a type.
2811class TypeDecl : public NamedDecl {
2812 friend class ASTContext;
2813
2814 /// This indicates the Type object that represents
2815 /// this TypeDecl. It is a cache maintained by
2816 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2817 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2818 mutable const Type *TypeForDecl = nullptr;
2819
2820 /// The start of the source range for this declaration.
2821 SourceLocation LocStart;
2822
2823 void anchor() override;
2824
2825protected:
2826 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2827 SourceLocation StartL = SourceLocation())
2828 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2829
2830public:
2831 // Low-level accessor. If you just want the type defined by this node,
2832 // check out ASTContext::getTypeDeclType or one of
2833 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2834 // already know the specific kind of node this is.
2835 const Type *getTypeForDecl() const { return TypeForDecl; }
2836 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2837
2838 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2839 void setLocStart(SourceLocation L) { LocStart = L; }
2840 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2841 if (LocStart.isValid())
2842 return SourceRange(LocStart, getLocation());
2843 else
2844 return SourceRange(getLocation());
2845 }
2846
2847 // Implement isa/cast/dyncast/etc.
2848 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2849 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2850};
2851
2852/// Base class for declarations which introduce a typedef-name.
2853class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2854 struct LLVM_ALIGNAS(8)alignas(8) ModedTInfo {
2855 TypeSourceInfo *first;
2856 QualType second;
2857 };
2858
2859 /// If int part is 0, we have not computed IsTransparentTag.
2860 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2861 mutable llvm::PointerIntPair<
2862 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2863 MaybeModedTInfo;
2864
2865 void anchor() override;
2866
2867protected:
2868 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2869 SourceLocation StartLoc, SourceLocation IdLoc,
2870 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2871 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2872 MaybeModedTInfo(TInfo, 0) {}
2873
2874 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2875
2876 TypedefNameDecl *getNextRedeclarationImpl() override {
2877 return getNextRedeclaration();
2878 }
2879
2880 TypedefNameDecl *getPreviousDeclImpl() override {
2881 return getPreviousDecl();
2882 }
2883
2884 TypedefNameDecl *getMostRecentDeclImpl() override {
2885 return getMostRecentDecl();
2886 }
2887
2888public:
2889 using redecl_range = redeclarable_base::redecl_range;
2890 using redecl_iterator = redeclarable_base::redecl_iterator;
2891
2892 using redeclarable_base::redecls_begin;
2893 using redeclarable_base::redecls_end;
2894 using redeclarable_base::redecls;
2895 using redeclarable_base::getPreviousDecl;
2896 using redeclarable_base::getMostRecentDecl;
2897 using redeclarable_base::isFirstDecl;
2898
2899 bool isModed() const {
2900 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
2901 }
2902
2903 TypeSourceInfo *getTypeSourceInfo() const {
2904 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
2905 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
2906 }
2907
2908 QualType getUnderlyingType() const {
2909 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
2910 : MaybeModedTInfo.getPointer()
2911 .get<TypeSourceInfo *>()
2912 ->getType();
2913 }
2914
2915 void setTypeSourceInfo(TypeSourceInfo *newType) {
2916 MaybeModedTInfo.setPointer(newType);
2917 }
2918
2919 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2920 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
2921 ModedTInfo({unmodedTSI, modedTy}));
2922 }
2923
2924 /// Retrieves the canonical declaration of this typedef-name.
2925 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2926 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2927
2928 /// Retrieves the tag declaration for which this is the typedef name for
2929 /// linkage purposes, if any.
2930 ///
2931 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2932 /// this typedef declaration.
2933 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2934
2935 /// Determines if this typedef shares a name and spelling location with its
2936 /// underlying tag type, as is the case with the NS_ENUM macro.
2937 bool isTransparentTag() const {
2938 if (MaybeModedTInfo.getInt())
2939 return MaybeModedTInfo.getInt() & 0x2;
2940 return isTransparentTagSlow();
2941 }
2942
2943 // Implement isa/cast/dyncast/etc.
2944 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2945 static bool classofKind(Kind K) {
2946 return K >= firstTypedefName && K <= lastTypedefName;
2947 }
2948
2949private:
2950 bool isTransparentTagSlow() const;
2951};
2952
2953/// Represents the declaration of a typedef-name via the 'typedef'
2954/// type specifier.
2955class TypedefDecl : public TypedefNameDecl {
2956 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2957 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2958 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2959
2960public:
2961 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2962 SourceLocation StartLoc, SourceLocation IdLoc,
2963 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2964 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2965
2966 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2967
2968 // Implement isa/cast/dyncast/etc.
2969 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2970 static bool classofKind(Kind K) { return K == Typedef; }
2971};
2972
2973/// Represents the declaration of a typedef-name via a C++11
2974/// alias-declaration.
2975class TypeAliasDecl : public TypedefNameDecl {
2976 /// The template for which this is the pattern, if any.
2977 TypeAliasTemplateDecl *Template;
2978
2979 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2980 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2981 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2982 Template(nullptr) {}
2983
2984public:
2985 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2986 SourceLocation StartLoc, SourceLocation IdLoc,
2987 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2988 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2989
2990 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2991
2992 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2993 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2994
2995 // Implement isa/cast/dyncast/etc.
2996 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2997 static bool classofKind(Kind K) { return K == TypeAlias; }
2998};
2999
3000/// Represents the declaration of a struct/union/class/enum.
3001class TagDecl
3002 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
3003public:
3004 // This is really ugly.
3005 using TagKind = TagTypeKind;
3006
3007private:
3008 // FIXME: This can be packed into the bitfields in Decl.
3009 /// The TagKind enum.
3010 unsigned TagDeclKind : 3;
3011
3012 /// True if this is a definition ("struct foo {};"), false if it is a
3013 /// declaration ("struct foo;"). It is not considered a definition
3014 /// until the definition has been fully processed.
3015 unsigned IsCompleteDefinition : 1;
3016
3017protected:
3018 /// True if this is currently being defined.
3019 unsigned IsBeingDefined : 1;
3020
3021private:
3022 /// True if this tag declaration is "embedded" (i.e., defined or declared
3023 /// for the very first time) in the syntax of a declarator.
3024 unsigned IsEmbeddedInDeclarator : 1;
3025
3026 /// True if this tag is free standing, e.g. "struct foo;".
3027 unsigned IsFreeStanding : 1;
3028
3029protected:
3030 // These are used by (and only defined for) EnumDecl.
3031 unsigned NumPositiveBits : 8;
3032 unsigned NumNegativeBits : 8;
3033
3034 /// True if this tag declaration is a scoped enumeration. Only
3035 /// possible in C++11 mode.
3036 unsigned IsScoped : 1;
3037
3038 /// If this tag declaration is a scoped enum,
3039 /// then this is true if the scoped enum was declared using the class
3040 /// tag, false if it was declared with the struct tag. No meaning is
3041 /// associated if this tag declaration is not a scoped enum.
3042 unsigned IsScopedUsingClassTag : 1;
3043
3044 /// True if this is an enumeration with fixed underlying type. Only
3045 /// possible in C++11, Microsoft extensions, or Objective C mode.
3046 unsigned IsFixed : 1;
3047
3048 /// Indicates whether it is possible for declarations of this kind
3049 /// to have an out-of-date definition.
3050 ///
3051 /// This option is only enabled when modules are enabled.
3052 unsigned MayHaveOutOfDateDef : 1;
3053
3054 /// Has the full definition of this type been required by a use somewhere in
3055 /// the TU.
3056 unsigned IsCompleteDefinitionRequired : 1;
3057
3058private:
3059 SourceRange BraceRange;
3060
3061 // A struct representing syntactic qualifier info,
3062 // to be used for the (uncommon) case of out-of-line declarations.
3063 using ExtInfo = QualifierInfo;
3064
3065 /// \brief If the (out-of-line) tag declaration name
3066 /// is qualified, it points to the qualifier info (nns and range);
3067 /// otherwise, if the tag declaration is anonymous and it is part of
3068 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3069 /// otherwise, if the tag declaration is anonymous and it is used as a
3070 /// declaration specifier for variables, it points to the first VarDecl (used
3071 /// for mangling);
3072 /// otherwise, it is a null (TypedefNameDecl) pointer.
3073 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3074
3075 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3076 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3077 const ExtInfo *getExtInfo() const {
3078 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3079 }
3080
3081protected:
3082 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3083 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3084 SourceLocation StartL)
3085 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3086 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
3087 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
3088 IsCompleteDefinitionRequired(false),
3089 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3090 assert((DK != Enum || TK == TTK_Enum) &&(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 3091, __extension__ __PRETTY_FUNCTION__))
3091 "EnumDecl not matched with TTK_Enum")(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 3091, __extension__ __PRETTY_FUNCTION__))
;
3092 setPreviousDecl(PrevDecl);
3093 }
3094
3095 using redeclarable_base = Redeclarable<TagDecl>;
3096
3097 TagDecl *getNextRedeclarationImpl() override {
3098 return getNextRedeclaration();
3099 }
3100
3101 TagDecl *getPreviousDeclImpl() override {
3102 return getPreviousDecl();
3103 }
3104
3105 TagDecl *getMostRecentDeclImpl() override {
3106 return getMostRecentDecl();
3107 }
3108
3109 /// @brief Completes the definition of this tag declaration.
3110 ///
3111 /// This is a helper function for derived classes.
3112 void completeDefinition();
3113
3114public:
3115 friend class ASTDeclReader;
3116 friend class ASTDeclWriter;
3117
3118 using redecl_range = redeclarable_base::redecl_range;
3119 using redecl_iterator = redeclarable_base::redecl_iterator;
3120
3121 using redeclarable_base::redecls_begin;
3122 using redeclarable_base::redecls_end;
3123 using redeclarable_base::redecls;
3124 using redeclarable_base::getPreviousDecl;
3125 using redeclarable_base::getMostRecentDecl;
3126 using redeclarable_base::isFirstDecl;
3127
3128 SourceRange getBraceRange() const { return BraceRange; }
3129 void setBraceRange(SourceRange R) { BraceRange = R; }
3130
3131 /// Return SourceLocation representing start of source
3132 /// range ignoring outer template declarations.
3133 SourceLocation getInnerLocStart() const { return getLocStart(); }
3134
3135 /// Return SourceLocation representing start of source
3136 /// range taking into account any outer template declarations.
3137 SourceLocation getOuterLocStart() const;
3138 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3139
3140 TagDecl *getCanonicalDecl() override;
3141 const TagDecl *getCanonicalDecl() const {
3142 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3143 }
3144
3145 /// Return true if this declaration is a completion definition of the type.
3146 /// Provided for consistency.
3147 bool isThisDeclarationADefinition() const {
3148 return isCompleteDefinition();
3149 }
3150
3151 /// Return true if this decl has its body fully specified.
3152 bool isCompleteDefinition() const {
3153 return IsCompleteDefinition;
3154 }
3155
3156 /// \brief Return true if this complete decl is
3157 /// required to be complete for some existing use.
3158 bool isCompleteDefinitionRequired() const {
3159 return IsCompleteDefinitionRequired;
3160 }
3161
3162 /// Return true if this decl is currently being defined.
3163 bool isBeingDefined() const {
3164 return IsBeingDefined;
3165 }
3166
3167 bool isEmbeddedInDeclarator() const {
3168 return IsEmbeddedInDeclarator;
3169 }
3170 void setEmbeddedInDeclarator(bool isInDeclarator) {
3171 IsEmbeddedInDeclarator = isInDeclarator;
3172 }
3173
3174 bool isFreeStanding() const { return IsFreeStanding; }
3175 void setFreeStanding(bool isFreeStanding = true) {
3176 IsFreeStanding = isFreeStanding;
3177 }
3178
3179 /// \brief Whether this declaration declares a type that is
3180 /// dependent, i.e., a type that somehow depends on template
3181 /// parameters.
3182 bool isDependentType() const { return isDependentContext(); }
3183
3184 /// Starts the definition of this tag declaration.
3185 ///
3186 /// This method should be invoked at the beginning of the definition
3187 /// of this tag declaration. It will set the tag type into a state
3188 /// where it is in the process of being defined.
3189 void startDefinition();
3190
3191 /// Returns the TagDecl that actually defines this
3192 /// struct/union/class/enum. When determining whether or not a
3193 /// struct/union/class/enum has a definition, one should use this
3194 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3195 /// whether or not a specific TagDecl is defining declaration, not
3196 /// whether or not the struct/union/class/enum type is defined.
3197 /// This method returns NULL if there is no TagDecl that defines
3198 /// the struct/union/class/enum.
3199 TagDecl *getDefinition() const;
3200
3201 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
3202
3203 void setCompleteDefinitionRequired(bool V = true) {
3204 IsCompleteDefinitionRequired = V;
3205 }
3206
3207 StringRef getKindName() const {
3208 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3209 }
3210
3211 TagKind getTagKind() const {
3212 return TagKind(TagDeclKind);
3213 }
3214
3215 void setTagKind(TagKind TK) { TagDeclKind = TK; }
3216
3217 bool isStruct() const { return getTagKind() == TTK_Struct; }
3218 bool isInterface() const { return getTagKind() == TTK_Interface; }
3219 bool isClass() const { return getTagKind() == TTK_Class; }
3220 bool isUnion() const { return getTagKind() == TTK_Union; }
3221 bool isEnum() const { return getTagKind() == TTK_Enum; }
3222
3223 /// Is this tag type named, either directly or via being defined in
3224 /// a typedef of this type?
3225 ///
3226 /// C++11 [basic.link]p8:
3227 /// A type is said to have linkage if and only if:
3228 /// - it is a class or enumeration type that is named (or has a
3229 /// name for linkage purposes) and the name has linkage; ...
3230 /// C++11 [dcl.typedef]p9:
3231 /// If the typedef declaration defines an unnamed class (or enum),
3232 /// the first typedef-name declared by the declaration to be that
3233 /// class type (or enum type) is used to denote the class type (or
3234 /// enum type) for linkage purposes only.
3235 ///
3236 /// C does not have an analogous rule, but the same concept is
3237 /// nonetheless useful in some places.
3238 bool hasNameForLinkage() const {
3239 return (getDeclName() || getTypedefNameForAnonDecl());
3240 }
3241
3242 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3243 return hasExtInfo() ? nullptr
3244 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3245 }
3246
3247 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3248
3249 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3250 /// declaration, if it was present in the source.
3251 NestedNameSpecifier *getQualifier() const {
3252 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3253 : nullptr;
3254 }
3255
3256 /// \brief Retrieve the nested-name-specifier (with source-location
3257 /// information) that qualifies the name of this declaration, if it was
3258 /// present in the source.
3259 NestedNameSpecifierLoc getQualifierLoc() const {
3260 return hasExtInfo() ? getExtInfo()->QualifierLoc
3261 : NestedNameSpecifierLoc();
3262 }
3263
3264 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3265
3266 unsigned getNumTemplateParameterLists() const {
3267 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3268 }
3269
3270 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3271 assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 3271, __extension__ __PRETTY_FUNCTION__))
;
3272 return getExtInfo()->TemplParamLists[i];
3273 }
3274
3275 void setTemplateParameterListsInfo(ASTContext &Context,
3276 ArrayRef<TemplateParameterList *> TPLists);
3277
3278 // Implement isa/cast/dyncast/etc.
3279 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3280 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3281
3282 static DeclContext *castToDeclContext(const TagDecl *D) {
3283 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3284 }
3285
3286 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3287 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3288 }
3289};
3290
3291/// Represents an enum. In C++11, enums can be forward-declared
3292/// with a fixed underlying type, and in C we allow them to be forward-declared
3293/// with no underlying type as an extension.
3294class EnumDecl : public TagDecl {
3295 /// This represent the integer type that the enum corresponds
3296 /// to for code generation purposes. Note that the enumerator constants may
3297 /// have a different type than this does.
3298 ///
3299 /// If the underlying integer type was explicitly stated in the source
3300 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3301 /// was automatically deduced somehow, and this is a Type*.
3302 ///
3303 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3304 /// some cases it won't.
3305 ///
3306 /// The underlying type of an enumeration never has any qualifiers, so
3307 /// we can get away with just storing a raw Type*, and thus save an
3308 /// extra pointer when TypeSourceInfo is needed.
3309 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3310
3311 /// The integer type that values of this type should
3312 /// promote to. In C, enumerators are generally of an integer type
3313 /// directly, but gcc-style large enumerators (and all enumerators
3314 /// in C++) are of the enum type instead.
3315 QualType PromotionType;
3316
3317 /// \brief If this enumeration is an instantiation of a member enumeration
3318 /// of a class template specialization, this is the member specialization
3319 /// information.
3320 MemberSpecializationInfo *SpecializationInfo = nullptr;
3321
3322 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3323 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3324 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3325 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3326 assert(Scoped || !ScopedUsingClassTag)(static_cast <bool> (Scoped || !ScopedUsingClassTag) ? void
(0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 3326, __extension__ __PRETTY_FUNCTION__))
;
3327 IntegerType = (const Type *)nullptr;
3328 NumNegativeBits = 0;
3329 NumPositiveBits = 0;
3330 IsScoped = Scoped;
3331 IsScopedUsingClassTag = ScopedUsingClassTag;
3332 IsFixed = Fixed;
3333 }
3334
3335 void anchor() override;
3336
3337 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3338 TemplateSpecializationKind TSK);
3339public:
3340 friend class ASTDeclReader;
3341
3342 EnumDecl *getCanonicalDecl() override {
3343 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3344 }
3345 const EnumDecl *getCanonicalDecl() const {
3346 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3347 }
3348
3349 EnumDecl *getPreviousDecl() {
3350 return cast_or_null<EnumDecl>(
3351 static_cast<TagDecl *>(this)->getPreviousDecl());
3352 }
3353 const EnumDecl *getPreviousDecl() const {
3354 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3355 }
3356
3357 EnumDecl *getMostRecentDecl() {
3358 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3359 }
3360 const EnumDecl *getMostRecentDecl() const {
3361 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3362 }
3363
3364 EnumDecl *getDefinition() const {
3365 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3366 }
3367
3368 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3369 SourceLocation StartLoc, SourceLocation IdLoc,
3370 IdentifierInfo *Id, EnumDecl *PrevDecl,
3371 bool IsScoped, bool IsScopedUsingClassTag,
3372 bool IsFixed);
3373 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3374
3375 /// When created, the EnumDecl corresponds to a
3376 /// forward-declared enum. This method is used to mark the
3377 /// declaration as being defined; its enumerators have already been
3378 /// added (via DeclContext::addDecl). NewType is the new underlying
3379 /// type of the enumeration type.
3380 void completeDefinition(QualType NewType,
3381 QualType PromotionType,
3382 unsigned NumPositiveBits,
3383 unsigned NumNegativeBits);
3384
3385 // Iterates through the enumerators of this enumeration.
3386 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3387 using enumerator_range =
3388 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3389
3390 enumerator_range enumerators() const {
3391 return enumerator_range(enumerator_begin(), enumerator_end());
3392 }
3393
3394 enumerator_iterator enumerator_begin() const {
3395 const EnumDecl *E = getDefinition();
3396 if (!E)
3397 E = this;
3398 return enumerator_iterator(E->decls_begin());
3399 }
3400
3401 enumerator_iterator enumerator_end() const {
3402 const EnumDecl *E = getDefinition();
3403 if (!E)
3404 E = this;
3405 return enumerator_iterator(E->decls_end());
3406 }
3407
3408 /// Return the integer type that enumerators should promote to.
3409 QualType getPromotionType() const { return PromotionType; }
3410
3411 /// Set the promotion type.
3412 void setPromotionType(QualType T) { PromotionType = T; }
3413
3414 /// Return the integer type this enum decl corresponds to.
3415 /// This returns a null QualType for an enum forward definition with no fixed
3416 /// underlying type.
3417 QualType getIntegerType() const {
3418 if (!IntegerType)
3419 return QualType();
3420 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3421 return QualType(T, 0);
3422 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3423 }
3424
3425 /// \brief Set the underlying integer type.
3426 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3427
3428 /// \brief Set the underlying integer type source info.
3429 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3430
3431 /// \brief Return the type source info for the underlying integer type,
3432 /// if no type source info exists, return 0.
3433 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3434 return IntegerType.dyn_cast<TypeSourceInfo*>();
3435 }
3436
3437 /// \brief Retrieve the source range that covers the underlying type if
3438 /// specified.
3439 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3440
3441 /// \brief Returns the width in bits required to store all the
3442 /// non-negative enumerators of this enum.
3443 unsigned getNumPositiveBits() const {
3444 return NumPositiveBits;
3445 }
3446 void setNumPositiveBits(unsigned Num) {
3447 NumPositiveBits = Num;
3448 assert(NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (NumPositiveBits == Num && "can't store this bitcount"
) ? void (0) : __assert_fail ("NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 3448, __extension__ __PRETTY_FUNCTION__))
;
3449 }
3450
3451 /// \brief Returns the width in bits required to store all the
3452 /// negative enumerators of this enum. These widths include
3453 /// the rightmost leading 1; that is:
3454 ///
3455 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3456 /// ------------------------ ------- -----------------
3457 /// -1 1111111 1
3458 /// -10 1110110 5
3459 /// -101 1001011 8
3460 unsigned getNumNegativeBits() const {
3461 return NumNegativeBits;
3462 }
3463 void setNumNegativeBits(unsigned Num) {
3464 NumNegativeBits = Num;
3465 }
3466
3467 /// \brief Returns true if this is a C++11 scoped enumeration.
3468 bool isScoped() const {
3469 return IsScoped;
3470 }
3471
3472 /// \brief Returns true if this is a C++11 scoped enumeration.
3473 bool isScopedUsingClassTag() const {
3474 return IsScopedUsingClassTag;
3475 }
3476
3477 /// \brief Returns true if this is an Objective-C, C++11, or
3478 /// Microsoft-style enumeration with a fixed underlying type.
3479 bool isFixed() const {
3480 return IsFixed;
3481 }
3482
3483 /// \brief Returns true if this can be considered a complete type.
3484 bool isComplete() const {
3485 // IntegerType is set for fixed type enums and non-fixed but implicitly
3486 // int-sized Microsoft enums.
3487 return isCompleteDefinition() || IntegerType;
3488 }
3489
3490 /// Returns true if this enum is either annotated with
3491 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3492 bool isClosed() const;
3493
3494 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3495 /// with enum_extensibility(open).
3496 bool isClosedFlag() const;
3497
3498 /// Returns true if this enum is annotated with neither flag_enum nor
3499 /// enum_extensibility(open).
3500 bool isClosedNonFlag() const;
3501
3502 /// \brief Retrieve the enum definition from which this enumeration could
3503 /// be instantiated, if it is an instantiation (rather than a non-template).
3504 EnumDecl *getTemplateInstantiationPattern() const;
3505
3506 /// \brief Returns the enumeration (declared within the template)
3507 /// from which this enumeration type was instantiated, or NULL if
3508 /// this enumeration was not instantiated from any template.
3509 EnumDecl *getInstantiatedFromMemberEnum() const;
3510
3511 /// \brief If this enumeration is a member of a specialization of a
3512 /// templated class, determine what kind of template specialization
3513 /// or instantiation this is.
3514 TemplateSpecializationKind getTemplateSpecializationKind() const;
3515
3516 /// \brief For an enumeration member that was instantiated from a member
3517 /// enumeration of a templated class, set the template specialiation kind.
3518 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3519 SourceLocation PointOfInstantiation = SourceLocation());
3520
3521 /// \brief If this enumeration is an instantiation of a member enumeration of
3522 /// a class template specialization, retrieves the member specialization
3523 /// information.
3524 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3525 return SpecializationInfo;
3526 }
3527
3528 /// \brief Specify that this enumeration is an instantiation of the
3529 /// member enumeration ED.
3530 void setInstantiationOfMemberEnum(EnumDecl *ED,
3531 TemplateSpecializationKind TSK) {
3532 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3533 }
3534
3535 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3536 static bool classofKind(Kind K) { return K == Enum; }
3537};
3538
3539/// Represents a struct/union/class. For example:
3540/// struct X; // Forward declaration, no "body".
3541/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3542/// This decl will be marked invalid if *any* members are invalid.
3543class RecordDecl : public TagDecl {
3544public:
3545 /// Enum that represents the different ways arguments are passed to and
3546 /// returned from function calls. This takes into account the target-specific
3547 /// and version-specific rules along with the rules determined by the
3548 /// language.
3549 enum ArgPassingKind : unsigned {
3550 /// The argument of this type can be passed directly in registers.
3551 APK_CanPassInRegs,
3552
3553 /// The argument of this type cannot be passed directly in registers.
3554 /// Records containing this type as a subobject are not forced to be passed
3555 /// indirectly. This value is used only in C++. This value is required by
3556 /// C++ because, in uncommon situations, it is possible for a class to have
3557 /// only trivial copy/move constructors even when one of its subobjects has
3558 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3559 /// constructor in the derived class is deleted).
3560 APK_CannotPassInRegs,
3561
3562 /// The argument of this type cannot be passed directly in registers.
3563 /// Records containing this type as a subobject are forced to be passed
3564 /// indirectly.
3565 APK_CanNeverPassInRegs
3566 };
3567
3568private:
3569 friend class DeclContext;
3570
3571 // FIXME: This can be packed into the bitfields in Decl.
3572 /// This is true if this struct ends with a flexible
3573 /// array member (e.g. int X[]) or if this union contains a struct that does.
3574 /// If so, this cannot be contained in arrays or other structs as a member.
3575 bool HasFlexibleArrayMember : 1;
3576
3577 /// Whether this is the type of an anonymous struct or union.
3578 bool AnonymousStructOrUnion : 1;
3579
3580 /// This is true if this struct has at least one member
3581 /// containing an Objective-C object pointer type.
3582 bool HasObjectMember : 1;
3583
3584 /// This is true if struct has at least one member of
3585 /// 'volatile' type.
3586 bool HasVolatileMember : 1;
3587
3588 /// Whether the field declarations of this record have been loaded
3589 /// from external storage. To avoid unnecessary deserialization of
3590 /// methods/nested types we allow deserialization of just the fields
3591 /// when needed.
3592 mutable bool LoadedFieldsFromExternalStorage : 1;
3593
3594 /// Basic properties of non-trivial C structs.
3595 bool NonTrivialToPrimitiveDefaultInitialize : 1;
3596 bool NonTrivialToPrimitiveCopy : 1;
3597 bool NonTrivialToPrimitiveDestroy : 1;
3598
3599 /// Indicates whether this struct is destroyed in the callee. This flag is
3600 /// meaningless when Microsoft ABI is used since parameters are always
3601 /// destroyed in the callee.
3602 ///
3603 /// Please note that MSVC won't merge adjacent bitfields if they don't have
3604 /// the same type.
3605 uint8_t ParamDestroyedInCallee : 1;
3606
3607 /// Represents the way this type is passed to a function.
3608 uint8_t ArgPassingRestrictions : 2;
3609
3610protected:
3611 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3612 SourceLocation StartLoc, SourceLocation IdLoc,
3613 IdentifierInfo *Id, RecordDecl *PrevDecl);
3614
3615public:
3616 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3617 SourceLocation StartLoc, SourceLocation IdLoc,
3618 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3619 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3620
3621 RecordDecl *getPreviousDecl() {
3622 return cast_or_null<RecordDecl>(
3623 static_cast<TagDecl *>(this)->getPreviousDecl());
3624 }
3625 const RecordDecl *getPreviousDecl() const {
3626 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3627 }
3628
3629 RecordDecl *getMostRecentDecl() {
3630 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3631 }
3632 const RecordDecl *getMostRecentDecl() const {
3633 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3634 }
3635
3636 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3637 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3638
3639 /// Whether this is an anonymous struct or union. To be an anonymous
3640 /// struct or union, it must have been declared without a name and
3641 /// there must be no objects of this type declared, e.g.,
3642 /// @code
3643 /// union { int i; float f; };
3644 /// @endcode
3645 /// is an anonymous union but neither of the following are:
3646 /// @code
3647 /// union X { int i; float f; };
3648 /// union { int i; float f; } obj;
3649 /// @endcode
3650 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3651 void setAnonymousStructOrUnion(bool Anon) {
3652 AnonymousStructOrUnion = Anon;
3653 }
3654
3655 bool hasObjectMember() const { return HasObjectMember; }
3656 void setHasObjectMember (bool val) { HasObjectMember = val; }
3657
3658 bool hasVolatileMember() const { return HasVolatileMember; }
3659 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3660
3661 bool hasLoadedFieldsFromExternalStorage() const {
3662 return LoadedFieldsFromExternalStorage;
3663 }
3664 void setHasLoadedFieldsFromExternalStorage(bool val) {
3665 LoadedFieldsFromExternalStorage = val;
3666 }
3667
3668 /// Functions to query basic properties of non-trivial C structs.
3669 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3670 return NonTrivialToPrimitiveDefaultInitialize;
3671 }
3672
3673 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3674 NonTrivialToPrimitiveDefaultInitialize = V;
3675 }
3676
3677 bool isNonTrivialToPrimitiveCopy() const {
3678 return NonTrivialToPrimitiveCopy;
3679 }
3680
3681 void setNonTrivialToPrimitiveCopy(bool V) {
3682 NonTrivialToPrimitiveCopy = V;
3683 }
3684
3685 bool isNonTrivialToPrimitiveDestroy() const {
3686 return NonTrivialToPrimitiveDestroy;
3687 }
3688
3689 void setNonTrivialToPrimitiveDestroy(bool V) {
3690 NonTrivialToPrimitiveDestroy = V;
3691 }
3692
3693 /// Determine whether this class can be passed in registers. In C++ mode,
3694 /// it must have at least one trivial, non-deleted copy or move constructor.
3695 /// FIXME: This should be set as part of completeDefinition.
3696 bool canPassInRegisters() const {
3697 return getArgPassingRestrictions() == APK_CanPassInRegs;
3698 }
3699
3700 ArgPassingKind getArgPassingRestrictions() const {
3701 return static_cast<ArgPassingKind>(ArgPassingRestrictions);
3702 }
3703
3704 void setArgPassingRestrictions(ArgPassingKind Kind) {
3705 ArgPassingRestrictions = static_cast<uint8_t>(Kind);
3706 }
3707
3708 bool isParamDestroyedInCallee() const {
3709 return ParamDestroyedInCallee;
3710 }
3711
3712 void setParamDestroyedInCallee(bool V) {
3713 ParamDestroyedInCallee = V;
3714 }
3715
3716 /// \brief Determines whether this declaration represents the
3717 /// injected class name.
3718 ///
3719 /// The injected class name in C++ is the name of the class that
3720 /// appears inside the class itself. For example:
3721 ///
3722 /// \code
3723 /// struct C {
3724 /// // C is implicitly declared here as a synonym for the class name.
3725 /// };
3726 ///
3727 /// C::C c; // same as "C c;"
3728 /// \endcode
3729 bool isInjectedClassName() const;
3730
3731 /// \brief Determine whether this record is a class describing a lambda
3732 /// function object.
3733 bool isLambda() const;
3734
3735 /// \brief Determine whether this record is a record for captured variables in
3736 /// CapturedStmt construct.
3737 bool isCapturedRecord() const;
3738
3739 /// \brief Mark the record as a record for captured variables in CapturedStmt
3740 /// construct.
3741 void setCapturedRecord();
3742
3743 /// Returns the RecordDecl that actually defines
3744 /// this struct/union/class. When determining whether or not a
3745 /// struct/union/class is completely defined, one should use this
3746 /// method as opposed to 'isCompleteDefinition'.
3747 /// 'isCompleteDefinition' indicates whether or not a specific
3748 /// RecordDecl is a completed definition, not whether or not the
3749 /// record type is defined. This method returns NULL if there is
3750 /// no RecordDecl that defines the struct/union/tag.
3751 RecordDecl *getDefinition() const {
3752 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3753 }
3754
3755 // Iterator access to field members. The field iterator only visits
3756 // the non-static data members of this class, ignoring any static
3757 // data members, functions, constructors, destructors, etc.
3758 using field_iterator = specific_decl_iterator<FieldDecl>;
3759 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3760
3761 field_range fields() const { return field_range(field_begin(), field_end()); }
3762 field_iterator field_begin() const;
3763
3764 field_iterator field_end() const {
3765 return field_iterator(decl_iterator());
3766 }
3767
3768 // Whether there are any fields (non-static data members) in this record.
3769 bool field_empty() const {
3770 return field_begin() == field_end();
3771 }
3772
3773 /// Note that the definition of this type is now complete.
3774 virtual void completeDefinition();
3775
3776 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3777 static bool classofKind(Kind K) {
3778 return K >= firstRecord && K <= lastRecord;
3779 }
3780
3781 /// \brief Get whether or not this is an ms_struct which can
3782 /// be turned on with an attribute, pragma, or -mms-bitfields
3783 /// commandline option.
3784 bool isMsStruct(const ASTContext &C) const;
3785
3786 /// \brief Whether we are allowed to insert extra padding between fields.
3787 /// These padding are added to help AddressSanitizer detect
3788 /// intra-object-overflow bugs.
3789 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3790
3791 /// Finds the first data member which has a name.
3792 /// nullptr is returned if no named data member exists.
3793 const FieldDecl *findFirstNamedDataMember() const;
3794
3795private:
3796 /// \brief Deserialize just the fields.
3797 void LoadFieldsFromExternalStorage() const;
3798};
3799
3800class FileScopeAsmDecl : public Decl {
3801 StringLiteral *AsmString;
3802 SourceLocation RParenLoc;
3803
3804 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3805 SourceLocation StartL, SourceLocation EndL)
3806 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3807
3808 virtual void anchor();
3809
3810public:
3811 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3812 StringLiteral *Str, SourceLocation AsmLoc,
3813 SourceLocation RParenLoc);
3814
3815 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3816
3817 SourceLocation getAsmLoc() const { return getLocation(); }
3818 SourceLocation getRParenLoc() const { return RParenLoc; }
3819 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3820 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3821 return SourceRange(getAsmLoc(), getRParenLoc());
3822 }
3823
3824 const StringLiteral *getAsmString() const { return AsmString; }
3825 StringLiteral *getAsmString() { return AsmString; }
3826 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3827
3828 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3829 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3830};
3831
3832/// Pepresents a block literal declaration, which is like an
3833/// unnamed FunctionDecl. For example:
3834/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3835class BlockDecl : public Decl, public DeclContext {
3836public:
3837 /// A class which contains all the information about a particular
3838 /// captured value.
3839 class Capture {
3840 enum {
3841 flag_isByRef = 0x1,
3842 flag_isNested = 0x2
3843 };
3844
3845 /// The variable being captured.
3846 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3847
3848 /// The copy expression, expressed in terms of a DeclRef (or
3849 /// BlockDeclRef) to the captured variable. Only required if the
3850 /// variable has a C++ class type.
3851 Expr *CopyExpr;
3852
3853 public:
3854 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3855 : VariableAndFlags(variable,
3856 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3857 CopyExpr(copy) {}
3858
3859 /// The variable being captured.
3860 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3861
3862 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3863 /// variable.
3864 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3865
3866 /// Whether this is a nested capture, i.e. the variable captured
3867 /// is not from outside the immediately enclosing function/block.
3868 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3869
3870 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3871 Expr *getCopyExpr() const { return CopyExpr; }
3872 void setCopyExpr(Expr *e) { CopyExpr = e; }
3873 };
3874
3875private:
3876 // FIXME: This can be packed into the bitfields in Decl.
3877 bool IsVariadic : 1;
3878 bool CapturesCXXThis : 1;
3879 bool BlockMissingReturnType : 1;
3880 bool IsConversionFromLambda : 1;
3881
3882 /// A bit that indicates this block is passed directly to a function as a
3883 /// non-escaping parameter.
3884 bool DoesNotEscape : 1;
3885
3886 /// A new[]'d array of pointers to ParmVarDecls for the formal
3887 /// parameters of this function. This is null if a prototype or if there are
3888 /// no formals.
3889 ParmVarDecl **ParamInfo = nullptr;
3890 unsigned NumParams = 0;
3891
3892 Stmt *Body = nullptr;
3893 TypeSourceInfo *SignatureAsWritten = nullptr;
3894
3895 const Capture *Captures = nullptr;
3896 unsigned NumCaptures = 0;
3897
3898 unsigned ManglingNumber = 0;
3899 Decl *ManglingContextDecl = nullptr;
3900
3901protected:
3902 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3903 : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false),
3904 CapturesCXXThis(false), BlockMissingReturnType(true),
3905 IsConversionFromLambda(false), DoesNotEscape(false) {}
3906
3907public:
3908 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3909 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3910
3911 SourceLocation getCaretLocation() const { return getLocation(); }
3912
3913 bool isVariadic() const { return IsVariadic; }
3914 void setIsVariadic(bool value) { IsVariadic = value; }
3915
3916 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3917 Stmt *getBody() const override { return (Stmt*) Body; }
3918 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3919
3920 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3921 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3922
3923 // ArrayRef access to formal parameters.
3924 ArrayRef<ParmVarDecl *> parameters() const {
3925 return {ParamInfo, getNumParams()};
3926 }
3927 MutableArrayRef<ParmVarDecl *> parameters() {
3928 return {ParamInfo, getNumParams()};
3929 }
3930
3931 // Iterator access to formal parameters.
3932 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3933 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3934
3935 bool param_empty() const { return parameters().empty(); }
3936 param_iterator param_begin() { return parameters().begin(); }
3937 param_iterator param_end() { return parameters().end(); }
3938 param_const_iterator param_begin() const { return parameters().begin(); }
3939 param_const_iterator param_end() const { return parameters().end(); }
3940 size_t param_size() const { return parameters().size(); }
3941
3942 unsigned getNumParams() const { return NumParams; }
3943
3944 const ParmVarDecl *getParamDecl(unsigned i) const {
3945 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 3945, __extension__ __PRETTY_FUNCTION__))
;
3946 return ParamInfo[i];
3947 }
3948 ParmVarDecl *getParamDecl(unsigned i) {
3949 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 3949, __extension__ __PRETTY_FUNCTION__))
;
3950 return ParamInfo[i];
3951 }
3952
3953 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3954
3955 /// True if this block (or its nested blocks) captures
3956 /// anything of local storage from its enclosing scopes.
3957 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3958
3959 /// Returns the number of captured variables.
3960 /// Does not include an entry for 'this'.
3961 unsigned getNumCaptures() const { return NumCaptures; }
3962
3963 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3964
3965 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3966
3967 capture_const_iterator capture_begin() const { return captures().begin(); }
3968 capture_const_iterator capture_end() const { return captures().end(); }
3969
3970 bool capturesCXXThis() const { return CapturesCXXThis; }
3971 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3972 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3973
3974 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3975 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3976
3977 bool doesNotEscape() const { return DoesNotEscape; }
3978 void setDoesNotEscape() { DoesNotEscape = true; }
3979
3980 bool capturesVariable(const VarDecl *var) const;
3981
3982 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3983 bool CapturesCXXThis);
3984
3985 unsigned getBlockManglingNumber() const {
3986 return ManglingNumber;
3987 }
3988
3989 Decl *getBlockManglingContextDecl() const {
3990 return ManglingContextDecl;
3991 }
3992
3993 void setBlockMangling(unsigned Number, Decl *Ctx) {
3994 ManglingNumber = Number;
3995 ManglingContextDecl = Ctx;
3996 }
3997
3998 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3999
4000 // Implement isa/cast/dyncast/etc.
4001 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4002 static bool classofKind(Kind K) { return K == Block; }
4003 static DeclContext *castToDeclContext(const BlockDecl *D) {
4004 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4005 }
4006 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4007 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4008 }
4009};
4010
4011/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4012class CapturedDecl final
4013 : public Decl,
4014 public DeclContext,
4015 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4016protected:
4017 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4018 return NumParams;
4019 }
4020
4021private:
4022 /// \brief The number of parameters to the outlined function.
4023 unsigned NumParams;
4024
4025 /// \brief The position of context parameter in list of parameters.
4026 unsigned ContextParam;
4027
4028 /// \brief The body of the outlined function.
4029 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4030
4031 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4032
4033 ImplicitParamDecl *const *getParams() const {
4034 return getTrailingObjects<ImplicitParamDecl *>();
4035 }
4036
4037 ImplicitParamDecl **getParams() {
4038 return getTrailingObjects<ImplicitParamDecl *>();
4039 }
4040
4041public:
4042 friend class ASTDeclReader;
4043 friend class ASTDeclWriter;
4044 friend TrailingObjects;
4045
4046 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4047 unsigned NumParams);
4048 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4049 unsigned NumParams);
4050
4051 Stmt *getBody() const override;
4052 void setBody(Stmt *B);
4053
4054 bool isNothrow() const;
4055 void setNothrow(bool Nothrow = true);
4056
4057 unsigned getNumParams() const { return NumParams; }
4058
4059 ImplicitParamDecl *getParam(unsigned i) const {
4060 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4060, __extension__ __PRETTY_FUNCTION__))
;
4061 return getParams()[i];
4062 }
4063 void setParam(unsigned i, ImplicitParamDecl *P) {
4064 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4064, __extension__ __PRETTY_FUNCTION__))
;
4065 getParams()[i] = P;
4066 }
4067
4068 // ArrayRef interface to parameters.
4069 ArrayRef<ImplicitParamDecl *> parameters() const {
4070 return {getParams(), getNumParams()};
4071 }
4072 MutableArrayRef<ImplicitParamDecl *> parameters() {
4073 return {getParams(), getNumParams()};
4074 }
4075
4076 /// \brief Retrieve the parameter containing captured variables.
4077 ImplicitParamDecl *getContextParam() const {
4078 assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void
(0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4078, __extension__ __PRETTY_FUNCTION__))
;
4079 return getParam(ContextParam);
4080 }
4081 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4082 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4082, __extension__ __PRETTY_FUNCTION__))
;
4083 ContextParam = i;
4084 setParam(i, P);
4085 }
4086 unsigned getContextParamPosition() const { return ContextParam; }
4087
4088 using param_iterator = ImplicitParamDecl *const *;
4089 using param_range = llvm::iterator_range<param_iterator>;
4090
4091 /// \brief Retrieve an iterator pointing to the first parameter decl.
4092 param_iterator param_begin() const { return getParams(); }
4093 /// \brief Retrieve an iterator one past the last parameter decl.
4094 param_iterator param_end() const { return getParams() + NumParams; }
4095
4096 // Implement isa/cast/dyncast/etc.
4097 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4098 static bool classofKind(Kind K) { return K == Captured; }
4099 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4100 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4101 }
4102 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4103 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4104 }
4105};
4106
4107/// \brief Describes a module import declaration, which makes the contents
4108/// of the named module visible in the current translation unit.
4109///
4110/// An import declaration imports the named module (or submodule). For example:
4111/// \code
4112/// @import std.vector;
4113/// \endcode
4114///
4115/// Import declarations can also be implicitly generated from
4116/// \#include/\#import directives.
4117class ImportDecl final : public Decl,
4118 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4119 friend class ASTContext;
4120 friend class ASTDeclReader;
4121 friend class ASTReader;
4122 friend TrailingObjects;
4123
4124 /// \brief The imported module, along with a bit that indicates whether
4125 /// we have source-location information for each identifier in the module
4126 /// name.
4127 ///
4128 /// When the bit is false, we only have a single source location for the
4129 /// end of the import declaration.
4130 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4131
4132 /// \brief The next import in the list of imports local to the translation
4133 /// unit being parsed (not loaded from an AST file).
4134 ImportDecl *NextLocalImport = nullptr;
4135
4136 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4137 ArrayRef<SourceLocation> IdentifierLocs);
4138
4139 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4140 SourceLocation EndLoc);
4141
4142 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4143
4144public:
4145 /// \brief Create a new module import declaration.
4146 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4147 SourceLocation StartLoc, Module *Imported,
4148 ArrayRef<SourceLocation> IdentifierLocs);
4149
4150 /// \brief Create a new module import declaration for an implicitly-generated
4151 /// import.
4152 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4153 SourceLocation StartLoc, Module *Imported,
4154 SourceLocation EndLoc);
4155
4156 /// \brief Create a new, deserialized module import declaration.
4157 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4158 unsigned NumLocations);
4159
4160 /// \brief Retrieve the module that was imported by the import declaration.
4161 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4162
4163 /// \brief Retrieves the locations of each of the identifiers that make up
4164 /// the complete module name in the import declaration.
4165 ///
4166 /// This will return an empty array if the locations of the individual
4167 /// identifiers aren't available.
4168 ArrayRef<SourceLocation> getIdentifierLocs() const;
4169
4170 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4171
4172 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4173 static bool classofKind(Kind K) { return K == Import; }
4174};
4175
4176/// \brief Represents a C++ Modules TS module export declaration.
4177///
4178/// For example:
4179/// \code
4180/// export void foo();
4181/// \endcode
4182class ExportDecl final : public Decl, public DeclContext {
4183 virtual void anchor();
4184
4185private:
4186 friend class ASTDeclReader;
4187
4188 /// \brief The source location for the right brace (if valid).
4189 SourceLocation RBraceLoc;
4190
4191 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4192 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4193 RBraceLoc(SourceLocation()) {}
4194
4195public:
4196 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4197 SourceLocation ExportLoc);
4198 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4199
4200 SourceLocation getExportLoc() const { return getLocation(); }
4201 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4202 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4203
4204 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
4205 if (RBraceLoc.isValid())
4206 return RBraceLoc;
4207 // No braces: get the end location of the (only) declaration in context
4208 // (if present).
4209 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
4210 }
4211
4212 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4213 return SourceRange(getLocation(), getLocEnd());
4214 }
4215
4216 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4217 static bool classofKind(Kind K) { return K == Export; }
4218 static DeclContext *castToDeclContext(const ExportDecl *D) {
4219 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4220 }
4221 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4222 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4223 }
4224};
4225
4226/// Represents an empty-declaration.
4227class EmptyDecl : public Decl {
4228 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4229
4230 virtual void anchor();
4231
4232public:
4233 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4234 SourceLocation L);
4235 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4236
4237 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4238 static bool classofKind(Kind K) { return K == Empty; }
4239};
4240
4241/// Insertion operator for diagnostics. This allows sending NamedDecl's
4242/// into a diagnostic with <<.
4243inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4244 const NamedDecl* ND) {
4245 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4246 DiagnosticsEngine::ak_nameddecl);
4247 return DB;
4248}
4249inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4250 const NamedDecl* ND) {
4251 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4252 DiagnosticsEngine::ak_nameddecl);
4253 return PD;
4254}
4255
4256template<typename decl_type>
4257void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4258 // Note: This routine is implemented here because we need both NamedDecl
4259 // and Redeclarable to be defined.
4260 assert(RedeclLink.NextIsLatest() &&(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4261, __extension__ __PRETTY_FUNCTION__))
4261 "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.NextIsLatest() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4261, __extension__ __PRETTY_FUNCTION__))
;
4262
4263 if (PrevDecl) {
4264 // Point to previous. Make sure that this is actually the most recent
4265 // redeclaration, or we can build invalid chains. If the most recent
4266 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4267 First = PrevDecl->getFirstDecl();
4268 assert(First->RedeclLink.NextIsLatest() && "Expected first")(static_cast <bool> (First->RedeclLink.NextIsLatest(
) && "Expected first") ? void (0) : __assert_fail ("First->RedeclLink.NextIsLatest() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4268, __extension__ __PRETTY_FUNCTION__))
;
4269 decl_type *MostRecent = First->getNextRedeclaration();
4270 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4271
4272 // If the declaration was previously visible, a redeclaration of it remains
4273 // visible even if it wouldn't be visible by itself.
4274 static_cast<decl_type*>(this)->IdentifierNamespace |=
4275 MostRecent->getIdentifierNamespace() &
4276 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4277 } else {
4278 // Make this first.
4279 First = static_cast<decl_type*>(this);
4280 }
4281
4282 // First one will point to this one as latest.
4283 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4284
4285 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4286, __extension__ __PRETTY_FUNCTION__))
4286 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/Decl.h"
, 4286, __extension__ __PRETTY_FUNCTION__))
;
4287}
4288
4289// Inline function definitions.
4290
4291/// Check if the given decl is complete.
4292///
4293/// We use this function to break a cycle between the inline definitions in
4294/// Type.h and Decl.h.
4295inline bool IsEnumDeclComplete(EnumDecl *ED) {
4296 return ED->isComplete();
4297}
4298
4299/// Check if the given decl is scoped.
4300///
4301/// We use this function to break a cycle between the inline definitions in
4302/// Type.h and Decl.h.
4303inline bool IsEnumDeclScoped(EnumDecl *ED) {
4304 return ED->isScoped();
4305}
4306
4307} // namespace clang
4308
4309#endif // LLVM_CLANG_AST_DECL_H