Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 2482, column 26
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 SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp

1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/AttributeCommonInfo.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/StringExtras.h"
44#include <map>
45#include <set>
46
47using namespace clang;
48
49//===----------------------------------------------------------------------===//
50// CheckDefaultArgumentVisitor
51//===----------------------------------------------------------------------===//
52
53namespace {
54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55 /// the default argument of a parameter to determine whether it
56 /// contains any ill-formed subexpressions. For example, this will
57 /// diagnose the use of local variables or parameters within the
58 /// default argument expression.
59 class CheckDefaultArgumentVisitor
60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61 Expr *DefaultArg;
62 Sema *S;
63
64 public:
65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66 : DefaultArg(defarg), S(s) {}
67
68 bool VisitExpr(Expr *Node);
69 bool VisitDeclRefExpr(DeclRefExpr *DRE);
70 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71 bool VisitLambdaExpr(LambdaExpr *Lambda);
72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73 };
74
75 /// VisitExpr - Visit all of the children of this expression.
76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77 bool IsInvalid = false;
78 for (Stmt *SubStmt : Node->children())
79 IsInvalid |= Visit(SubStmt);
80 return IsInvalid;
81 }
82
83 /// VisitDeclRefExpr - Visit a reference to a declaration, to
84 /// determine whether this declaration can be used in the default
85 /// argument expression.
86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87 NamedDecl *Decl = DRE->getDecl();
88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89 // C++ [dcl.fct.default]p9
90 // Default arguments are evaluated each time the function is
91 // called. The order of evaluation of function arguments is
92 // unspecified. Consequently, parameters of a function shall not
93 // be used in default argument expressions, even if they are not
94 // evaluated. Parameters of a function declared before a default
95 // argument expression are in scope and can hide namespace and
96 // class member names.
97 return S->Diag(DRE->getBeginLoc(),
98 diag::err_param_default_argument_references_param)
99 << Param->getDeclName() << DefaultArg->getSourceRange();
100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101 // C++ [dcl.fct.default]p7
102 // Local variables shall not be used in default argument
103 // expressions.
104 if (VDecl->isLocalVarDecl())
105 return S->Diag(DRE->getBeginLoc(),
106 diag::err_param_default_argument_references_local)
107 << VDecl->getDeclName() << DefaultArg->getSourceRange();
108 }
109
110 return false;
111 }
112
113 /// VisitCXXThisExpr - Visit a C++ "this" expression.
114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115 // C++ [dcl.fct.default]p8:
116 // The keyword this shall not be used in a default argument of a
117 // member function.
118 return S->Diag(ThisE->getBeginLoc(),
119 diag::err_param_default_argument_references_this)
120 << ThisE->getSourceRange();
121 }
122
123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124 bool Invalid = false;
125 for (PseudoObjectExpr::semantics_iterator
126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127 Expr *E = *i;
128
129 // Look through bindings.
130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131 E = OVE->getSourceExpr();
132 assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?"
) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 132, __PRETTY_FUNCTION__))
;
133 }
134
135 Invalid |= Visit(E);
136 }
137 return Invalid;
138 }
139
140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141 // C++11 [expr.lambda.prim]p13:
142 // A lambda-expression appearing in a default argument shall not
143 // implicitly or explicitly capture any entity.
144 if (Lambda->capture_begin() == Lambda->capture_end())
145 return false;
146
147 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
148 }
149}
150
151void
152Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
156 return;
157
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161 if (!Proto)
162 return;
163
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165
166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
168 return;
169
170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171 EST = EST_BasicNoexcept;
172
173 switch (EST) {
174 case EST_Unparsed:
175 case EST_Uninstantiated:
176 case EST_Unevaluated:
177 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 177)
;
178
179 // If this function can throw any exceptions, make a note of that.
180 case EST_MSAny:
181 case EST_None:
182 // FIXME: Whichever we see last of MSAny and None determines our result.
183 // We should make a consistent, order-independent choice here.
184 ClearExceptions();
185 ComputedEST = EST;
186 return;
187 case EST_NoexceptFalse:
188 ClearExceptions();
189 ComputedEST = EST_None;
190 return;
191 // FIXME: If the call to this decl is using any of its default arguments, we
192 // need to search them for potentially-throwing calls.
193 // If this function has a basic noexcept, it doesn't affect the outcome.
194 case EST_BasicNoexcept:
195 case EST_NoexceptTrue:
196 case EST_NoThrow:
197 return;
198 // If we're still at noexcept(true) and there's a throw() callee,
199 // change to that specification.
200 case EST_DynamicNone:
201 if (ComputedEST == EST_BasicNoexcept)
202 ComputedEST = EST_DynamicNone;
203 return;
204 case EST_DependentNoexcept:
205 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 206)
206 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 206)
;
207 case EST_Dynamic:
208 break;
209 }
210 assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier."
) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 210, __PRETTY_FUNCTION__))
;
211 assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 212, __PRETTY_FUNCTION__))
212 "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 212, __PRETTY_FUNCTION__))
;
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217 Exceptions.push_back(E);
218}
219
220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221 if (!E || ComputedEST == EST_MSAny)
222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
245 if (Self->canThrow(E))
246 ComputedEST = EST_None;
247}
248
249bool
250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251 SourceLocation EqualLoc) {
252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270 if (Result.isInvalid())
271 return true;
272 Arg = Result.getAs<Expr>();
273
274 CheckCompletedExpr(Arg, EqualLoc);
275 Arg = MaybeCreateExprWithCleanups(Arg);
276
277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
279
280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
292 return false;
293}
294
295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
298void
299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
302 return;
303
304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
305 UnparsedDefaultArgLocs.erase(Param);
306
307 // Default arguments are only permitted in C++
308 if (!getLangOpts().CPlusPlus) {
309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
311 Param->setInvalidDecl();
312 return;
313 }
314
315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
321 // C++11 [dcl.fct.default]p3
322 // A default argument expression [...] shall not be specified for a
323 // parameter pack.
324 if (Param->isParameterPack()) {
325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326 << DefaultArg->getSourceRange();
327 return;
328 }
329
330 // Check that the default argument is well-formed
331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332 if (DefaultArgChecker.Visit(DefaultArg)) {
333 Param->setInvalidDecl();
334 return;
335 }
336
337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338}
339
340/// ActOnParamUnparsedDefaultArgument - We've seen a default
341/// argument for a function parameter, but we can't parse it yet
342/// because we're inside a class definition. Note that this default
343/// argument will be parsed later.
344void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345 SourceLocation EqualLoc,
346 SourceLocation ArgLoc) {
347 if (!param)
348 return;
349
350 ParmVarDecl *Param = cast<ParmVarDecl>(param);
351 Param->setUnparsedDefaultArg();
352 UnparsedDefaultArgLocs[Param] = ArgLoc;
353}
354
355/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356/// the default argument for the parameter param failed.
357void Sema::ActOnParamDefaultArgumentError(Decl *param,
358 SourceLocation EqualLoc) {
359 if (!param)
360 return;
361
362 ParmVarDecl *Param = cast<ParmVarDecl>(param);
363 Param->setInvalidDecl();
364 UnparsedDefaultArgLocs.erase(Param);
365 Param->setDefaultArg(new(Context)
366 OpaqueValueExpr(EqualLoc,
367 Param->getType().getNonReferenceType(),
368 VK_RValue));
369}
370
371/// CheckExtraCXXDefaultArguments - Check for any extra default
372/// arguments in the declarator, which is not a function declaration
373/// or definition and therefore is not permitted to have default
374/// arguments. This routine should be invoked for every declarator
375/// that is not a function declaration or definition.
376void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377 // C++ [dcl.fct.default]p3
378 // A default argument expression shall be specified only in the
379 // parameter-declaration-clause of a function declaration or in a
380 // template-parameter (14.1). It shall not be specified for a
381 // parameter pack. If it is specified in a
382 // parameter-declaration-clause, it shall not occur within a
383 // declarator or abstract-declarator of a parameter-declaration.
384 bool MightBeFunction = D.isFunctionDeclarationContext();
385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386 DeclaratorChunk &chunk = D.getTypeObject(i);
387 if (chunk.Kind == DeclaratorChunk::Function) {
388 if (MightBeFunction) {
389 // This is a function declaration. It can have default arguments, but
390 // keep looking in case its return type is a function type with default
391 // arguments.
392 MightBeFunction = false;
393 continue;
394 }
395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396 ++argIdx) {
397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398 if (Param->hasUnparsedDefaultArg()) {
399 std::unique_ptr<CachedTokens> Toks =
400 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401 SourceRange SR;
402 if (Toks->size() > 1)
403 SR = SourceRange((*Toks)[1].getLocation(),
404 Toks->back().getLocation());
405 else
406 SR = UnparsedDefaultArgLocs[Param];
407 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
408 << SR;
409 } else if (Param->getDefaultArg()) {
410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411 << Param->getDefaultArg()->getSourceRange();
412 Param->setDefaultArg(nullptr);
413 }
414 }
415 } else if (chunk.Kind != DeclaratorChunk::Paren) {
416 MightBeFunction = false;
417 }
418 }
419}
420
421static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424 if (!PVD->hasDefaultArg())
425 return false;
426 if (!PVD->hasInheritedDefaultArg())
427 return true;
428 }
429 return false;
430}
431
432/// MergeCXXFunctionDecl - Merge two declarations of the same C++
433/// function, once we already know that they have the same
434/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435/// error, false otherwise.
436bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437 Scope *S) {
438 bool Invalid = false;
439
440 // The declaration context corresponding to the scope is the semantic
441 // parent, unless this is a local function declaration, in which case
442 // it is that surrounding function.
443 DeclContext *ScopeDC = New->isLocalExternDecl()
444 ? New->getLexicalDeclContext()
445 : New->getDeclContext();
446
447 // Find the previous declaration for the purpose of default arguments.
448 FunctionDecl *PrevForDefaultArgs = Old;
449 for (/**/; PrevForDefaultArgs;
450 // Don't bother looking back past the latest decl if this is a local
451 // extern declaration; nothing else could work.
452 PrevForDefaultArgs = New->isLocalExternDecl()
453 ? nullptr
454 : PrevForDefaultArgs->getPreviousDecl()) {
455 // Ignore hidden declarations.
456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457 continue;
458
459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460 !New->isCXXClassMember()) {
461 // Ignore default arguments of old decl if they are not in
462 // the same scope and this is not an out-of-line definition of
463 // a member function.
464 continue;
465 }
466
467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468 // If only one of these is a local function declaration, then they are
469 // declared in different scopes, even though isDeclInScope may think
470 // they're in the same scope. (If both are local, the scope check is
471 // sufficient, and if neither is local, then they are in the same scope.)
472 continue;
473 }
474
475 // We found the right previous declaration.
476 break;
477 }
478
479 // C++ [dcl.fct.default]p4:
480 // For non-template functions, default arguments can be added in
481 // later declarations of a function in the same
482 // scope. Declarations in different scopes have completely
483 // distinct sets of default arguments. That is, declarations in
484 // inner scopes do not acquire default arguments from
485 // declarations in outer scopes, and vice versa. In a given
486 // function declaration, all parameters subsequent to a
487 // parameter with a default argument shall have default
488 // arguments supplied in this or previous declarations. A
489 // default argument shall not be redefined by a later
490 // declaration (not even to the same value).
491 //
492 // C++ [dcl.fct.default]p6:
493 // Except for member functions of class templates, the default arguments
494 // in a member function definition that appears outside of the class
495 // definition are added to the set of default arguments provided by the
496 // member function declaration in the class definition.
497 for (unsigned p = 0, NumParams = PrevForDefaultArgs
498 ? PrevForDefaultArgs->getNumParams()
499 : 0;
500 p < NumParams; ++p) {
501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
502 ParmVarDecl *NewParam = New->getParamDecl(p);
503
504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
505 bool NewParamHasDfl = NewParam->hasDefaultArg();
506
507 if (OldParamHasDfl && NewParamHasDfl) {
508 unsigned DiagDefaultParamID =
509 diag::err_param_default_argument_redefinition;
510
511 // MSVC accepts that default parameters be redefined for member functions
512 // of template class. The new default parameter's value is ignored.
513 Invalid = true;
514 if (getLangOpts().MicrosoftExt) {
515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
516 if (MD && MD->getParent()->getDescribedClassTemplate()) {
517 // Merge the old default argument into the new parameter.
518 NewParam->setHasInheritedDefaultArg();
519 if (OldParam->hasUninstantiatedDefaultArg())
520 NewParam->setUninstantiatedDefaultArg(
521 OldParam->getUninstantiatedDefaultArg());
522 else
523 NewParam->setDefaultArg(OldParam->getInit());
524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
525 Invalid = false;
526 }
527 }
528
529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530 // hint here. Alternatively, we could walk the type-source information
531 // for NewParam to find the last source location in the type... but it
532 // isn't worth the effort right now. This is the kind of test case that
533 // is hard to get right:
534 // int f(int);
535 // void g(int (*fp)(int) = f);
536 // void g(int (*fp)(int) = &f);
537 Diag(NewParam->getLocation(), DiagDefaultParamID)
538 << NewParam->getDefaultArgRange();
539
540 // Look for the function declaration where the default argument was
541 // actually written, which may be a declaration prior to Old.
542 for (auto Older = PrevForDefaultArgs;
543 OldParam->hasInheritedDefaultArg(); /**/) {
544 Older = Older->getPreviousDecl();
545 OldParam = Older->getParamDecl(p);
546 }
547
548 Diag(OldParam->getLocation(), diag::note_previous_definition)
549 << OldParam->getDefaultArgRange();
550 } else if (OldParamHasDfl) {
551 // Merge the old default argument into the new parameter unless the new
552 // function is a friend declaration in a template class. In the latter
553 // case the default arguments will be inherited when the friend
554 // declaration will be instantiated.
555 if (New->getFriendObjectKind() == Decl::FOK_None ||
556 !New->getLexicalDeclContext()->isDependentContext()) {
557 // It's important to use getInit() here; getDefaultArg()
558 // strips off any top-level ExprWithCleanups.
559 NewParam->setHasInheritedDefaultArg();
560 if (OldParam->hasUnparsedDefaultArg())
561 NewParam->setUnparsedDefaultArg();
562 else if (OldParam->hasUninstantiatedDefaultArg())
563 NewParam->setUninstantiatedDefaultArg(
564 OldParam->getUninstantiatedDefaultArg());
565 else
566 NewParam->setDefaultArg(OldParam->getInit());
567 }
568 } else if (NewParamHasDfl) {
569 if (New->getDescribedFunctionTemplate()) {
570 // Paragraph 4, quoted above, only applies to non-template functions.
571 Diag(NewParam->getLocation(),
572 diag::err_param_default_argument_template_redecl)
573 << NewParam->getDefaultArgRange();
574 Diag(PrevForDefaultArgs->getLocation(),
575 diag::note_template_prev_declaration)
576 << false;
577 } else if (New->getTemplateSpecializationKind()
578 != TSK_ImplicitInstantiation &&
579 New->getTemplateSpecializationKind() != TSK_Undeclared) {
580 // C++ [temp.expr.spec]p21:
581 // Default function arguments shall not be specified in a declaration
582 // or a definition for one of the following explicit specializations:
583 // - the explicit specialization of a function template;
584 // - the explicit specialization of a member function template;
585 // - the explicit specialization of a member function of a class
586 // template where the class template specialization to which the
587 // member function specialization belongs is implicitly
588 // instantiated.
589 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
590 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
591 << New->getDeclName()
592 << NewParam->getDefaultArgRange();
593 } else if (New->getDeclContext()->isDependentContext()) {
594 // C++ [dcl.fct.default]p6 (DR217):
595 // Default arguments for a member function of a class template shall
596 // be specified on the initial declaration of the member function
597 // within the class template.
598 //
599 // Reading the tea leaves a bit in DR217 and its reference to DR205
600 // leads me to the conclusion that one cannot add default function
601 // arguments for an out-of-line definition of a member function of a
602 // dependent type.
603 int WhichKind = 2;
604 if (CXXRecordDecl *Record
605 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
606 if (Record->getDescribedClassTemplate())
607 WhichKind = 0;
608 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
609 WhichKind = 1;
610 else
611 WhichKind = 2;
612 }
613
614 Diag(NewParam->getLocation(),
615 diag::err_param_default_argument_member_template_redecl)
616 << WhichKind
617 << NewParam->getDefaultArgRange();
618 }
619 }
620 }
621
622 // DR1344: If a default argument is added outside a class definition and that
623 // default argument makes the function a special member function, the program
624 // is ill-formed. This can only happen for constructors.
625 if (isa<CXXConstructorDecl>(New) &&
626 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
627 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
628 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
629 if (NewSM != OldSM) {
630 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
631 assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0)
: __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 631, __PRETTY_FUNCTION__))
;
632 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
633 << NewParam->getDefaultArgRange() << NewSM;
634 Diag(Old->getLocation(), diag::note_previous_declaration);
635 }
636 }
637
638 const FunctionDecl *Def;
639 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
640 // template has a constexpr specifier then all its declarations shall
641 // contain the constexpr specifier.
642 if (New->getConstexprKind() != Old->getConstexprKind()) {
643 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
644 << New << New->getConstexprKind() << Old->getConstexprKind();
645 Diag(Old->getLocation(), diag::note_previous_declaration);
646 Invalid = true;
647 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
648 Old->isDefined(Def) &&
649 // If a friend function is inlined but does not have 'inline'
650 // specifier, it is a definition. Do not report attribute conflict
651 // in this case, redefinition will be diagnosed later.
652 (New->isInlineSpecified() ||
653 New->getFriendObjectKind() == Decl::FOK_None)) {
654 // C++11 [dcl.fcn.spec]p4:
655 // If the definition of a function appears in a translation unit before its
656 // first declaration as inline, the program is ill-formed.
657 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
658 Diag(Def->getLocation(), diag::note_previous_definition);
659 Invalid = true;
660 }
661
662 // C++17 [temp.deduct.guide]p3:
663 // Two deduction guide declarations in the same translation unit
664 // for the same class template shall not have equivalent
665 // parameter-declaration-clauses.
666 if (isa<CXXDeductionGuideDecl>(New) &&
667 !New->isFunctionTemplateSpecialization()) {
668 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
669 Diag(Old->getLocation(), diag::note_previous_declaration);
670 }
671
672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673 // argument expression, that declaration shall be a definition and shall be
674 // the only declaration of the function or function template in the
675 // translation unit.
676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
677 functionDeclHasDefaultArgument(Old)) {
678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679 Diag(Old->getLocation(), diag::note_previous_declaration);
680 Invalid = true;
681 }
682
683 return Invalid;
684}
685
686NamedDecl *
687Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
688 MultiTemplateParamsArg TemplateParamLists) {
689 assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0
) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 689, __PRETTY_FUNCTION__))
;
690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
691
692 // The syntax only allows a decomposition declarator as a simple-declaration,
693 // a for-range-declaration, or a condition in Clang, but we parse it in more
694 // cases than that.
695 if (!D.mayHaveDecompositionDeclarator()) {
696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
697 << Decomp.getSourceRange();
698 return nullptr;
699 }
700
701 if (!TemplateParamLists.empty()) {
702 // FIXME: There's no rule against this, but there are also no rules that
703 // would actually make it usable, so we reject it for now.
704 Diag(TemplateParamLists.front()->getTemplateLoc(),
705 diag::err_decomp_decl_template);
706 return nullptr;
707 }
708
709 Diag(Decomp.getLSquareLoc(),
710 !getLangOpts().CPlusPlus17
711 ? diag::ext_decomp_decl
712 : D.getContext() == DeclaratorContext::ConditionContext
713 ? diag::ext_decomp_decl_cond
714 : diag::warn_cxx14_compat_decomp_decl)
715 << Decomp.getSourceRange();
716
717 // The semantic context is always just the current context.
718 DeclContext *const DC = CurContext;
719
720 // C++17 [dcl.dcl]/8:
721 // The decl-specifier-seq shall contain only the type-specifier auto
722 // and cv-qualifiers.
723 // C++2a [dcl.dcl]/8:
724 // If decl-specifier-seq contains any decl-specifier other than static,
725 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
726 auto &DS = D.getDeclSpec();
727 {
728 SmallVector<StringRef, 8> BadSpecifiers;
729 SmallVector<SourceLocation, 8> BadSpecifierLocs;
730 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
731 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
732 if (auto SCS = DS.getStorageClassSpec()) {
733 if (SCS == DeclSpec::SCS_static) {
734 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
735 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
736 } else {
737 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
738 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
739 }
740 }
741 if (auto TSCS = DS.getThreadStorageClassSpec()) {
742 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
743 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
744 }
745 if (DS.hasConstexprSpecifier()) {
746 BadSpecifiers.push_back(
747 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
748 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
749 }
750 if (DS.isInlineSpecified()) {
751 BadSpecifiers.push_back("inline");
752 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
753 }
754 if (!BadSpecifiers.empty()) {
755 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
756 Err << (int)BadSpecifiers.size()
757 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
758 // Don't add FixItHints to remove the specifiers; we do still respect
759 // them when building the underlying variable.
760 for (auto Loc : BadSpecifierLocs)
761 Err << SourceRange(Loc, Loc);
762 } else if (!CPlusPlus20Specifiers.empty()) {
763 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
764 getLangOpts().CPlusPlus2a
765 ? diag::warn_cxx17_compat_decomp_decl_spec
766 : diag::ext_decomp_decl_spec);
767 Warn << (int)CPlusPlus20Specifiers.size()
768 << llvm::join(CPlusPlus20Specifiers.begin(),
769 CPlusPlus20Specifiers.end(), " ");
770 for (auto Loc : CPlusPlus20SpecifierLocs)
771 Warn << SourceRange(Loc, Loc);
772 }
773 // We can't recover from it being declared as a typedef.
774 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
775 return nullptr;
776 }
777
778 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
779 QualType R = TInfo->getType();
780
781 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
782 UPPC_DeclarationType))
783 D.setInvalidType();
784
785 // The syntax only allows a single ref-qualifier prior to the decomposition
786 // declarator. No other declarator chunks are permitted. Also check the type
787 // specifier here.
788 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
789 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
790 (D.getNumTypeObjects() == 1 &&
791 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
792 Diag(Decomp.getLSquareLoc(),
793 (D.hasGroupingParens() ||
794 (D.getNumTypeObjects() &&
795 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
796 ? diag::err_decomp_decl_parens
797 : diag::err_decomp_decl_type)
798 << R;
799
800 // In most cases, there's no actual problem with an explicitly-specified
801 // type, but a function type won't work here, and ActOnVariableDeclarator
802 // shouldn't be called for such a type.
803 if (R->isFunctionType())
804 D.setInvalidType();
805 }
806
807 // Build the BindingDecls.
808 SmallVector<BindingDecl*, 8> Bindings;
809
810 // Build the BindingDecls.
811 for (auto &B : D.getDecompositionDeclarator().bindings()) {
812 // Check for name conflicts.
813 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
814 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
815 ForVisibleRedeclaration);
816 LookupName(Previous, S,
817 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
818
819 // It's not permitted to shadow a template parameter name.
820 if (Previous.isSingleResult() &&
821 Previous.getFoundDecl()->isTemplateParameter()) {
822 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
823 Previous.getFoundDecl());
824 Previous.clear();
825 }
826
827 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
828 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
829 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
830 /*AllowInlineNamespace*/false);
831 if (!Previous.empty()) {
832 auto *Old = Previous.getRepresentativeDecl();
833 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
834 Diag(Old->getLocation(), diag::note_previous_definition);
835 }
836
837 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
838 PushOnScopeChains(BD, S, true);
839 Bindings.push_back(BD);
840 ParsingInitForAutoVars.insert(BD);
841 }
842
843 // There are no prior lookup results for the variable itself, because it
844 // is unnamed.
845 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
846 Decomp.getLSquareLoc());
847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
848 ForVisibleRedeclaration);
849
850 // Build the variable that holds the non-decomposed object.
851 bool AddToScope = true;
852 NamedDecl *New =
853 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
854 MultiTemplateParamsArg(), AddToScope, Bindings);
855 if (AddToScope) {
856 S->AddDecl(New);
857 CurContext->addHiddenDecl(New);
858 }
859
860 if (isInOpenMPDeclareTargetContext())
861 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
862
863 return New;
864}
865
866static bool checkSimpleDecomposition(
867 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
868 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
869 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
870 if ((int64_t)Bindings.size() != NumElems) {
871 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
872 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
873 << (NumElems < Bindings.size());
874 return true;
875 }
876
877 unsigned I = 0;
878 for (auto *B : Bindings) {
879 SourceLocation Loc = B->getLocation();
880 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
881 if (E.isInvalid())
882 return true;
883 E = GetInit(Loc, E.get(), I++);
884 if (E.isInvalid())
885 return true;
886 B->setBinding(ElemType, E.get());
887 }
888
889 return false;
890}
891
892static bool checkArrayLikeDecomposition(Sema &S,
893 ArrayRef<BindingDecl *> Bindings,
894 ValueDecl *Src, QualType DecompType,
895 const llvm::APSInt &NumElems,
896 QualType ElemType) {
897 return checkSimpleDecomposition(
898 S, Bindings, Src, DecompType, NumElems, ElemType,
899 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
900 ExprResult E = S.ActOnIntegerConstant(Loc, I);
901 if (E.isInvalid())
902 return ExprError();
903 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
904 });
905}
906
907static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
908 ValueDecl *Src, QualType DecompType,
909 const ConstantArrayType *CAT) {
910 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
911 llvm::APSInt(CAT->getSize()),
912 CAT->getElementType());
913}
914
915static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
916 ValueDecl *Src, QualType DecompType,
917 const VectorType *VT) {
918 return checkArrayLikeDecomposition(
919 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
920 S.Context.getQualifiedType(VT->getElementType(),
921 DecompType.getQualifiers()));
922}
923
924static bool checkComplexDecomposition(Sema &S,
925 ArrayRef<BindingDecl *> Bindings,
926 ValueDecl *Src, QualType DecompType,
927 const ComplexType *CT) {
928 return checkSimpleDecomposition(
929 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
930 S.Context.getQualifiedType(CT->getElementType(),
931 DecompType.getQualifiers()),
932 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
933 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
934 });
935}
936
937static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
938 TemplateArgumentListInfo &Args) {
939 SmallString<128> SS;
940 llvm::raw_svector_ostream OS(SS);
941 bool First = true;
942 for (auto &Arg : Args.arguments()) {
943 if (!First)
944 OS << ", ";
945 Arg.getArgument().print(PrintingPolicy, OS);
946 First = false;
947 }
948 return OS.str();
949}
950
951static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
952 SourceLocation Loc, StringRef Trait,
953 TemplateArgumentListInfo &Args,
954 unsigned DiagID) {
955 auto DiagnoseMissing = [&] {
956 if (DiagID)
957 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
958 Args);
959 return true;
960 };
961
962 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
963 NamespaceDecl *Std = S.getStdNamespace();
964 if (!Std)
965 return DiagnoseMissing();
966
967 // Look up the trait itself, within namespace std. We can diagnose various
968 // problems with this lookup even if we've been asked to not diagnose a
969 // missing specialization, because this can only fail if the user has been
970 // declaring their own names in namespace std or we don't support the
971 // standard library implementation in use.
972 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
973 Loc, Sema::LookupOrdinaryName);
974 if (!S.LookupQualifiedName(Result, Std))
975 return DiagnoseMissing();
976 if (Result.isAmbiguous())
977 return true;
978
979 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
980 if (!TraitTD) {
981 Result.suppressDiagnostics();
982 NamedDecl *Found = *Result.begin();
983 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
984 S.Diag(Found->getLocation(), diag::note_declared_at);
985 return true;
986 }
987
988 // Build the template-id.
989 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
990 if (TraitTy.isNull())
991 return true;
992 if (!S.isCompleteType(Loc, TraitTy)) {
993 if (DiagID)
994 S.RequireCompleteType(
995 Loc, TraitTy, DiagID,
996 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
997 return true;
998 }
999
1000 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1001 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1001, __PRETTY_FUNCTION__))
;
1002
1003 // Look up the member of the trait type.
1004 S.LookupQualifiedName(TraitMemberLookup, RD);
1005 return TraitMemberLookup.isAmbiguous();
1006}
1007
1008static TemplateArgumentLoc
1009getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1010 uint64_t I) {
1011 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1012 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1013}
1014
1015static TemplateArgumentLoc
1016getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1017 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1018}
1019
1020namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1021
1022static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1023 llvm::APSInt &Size) {
1024 EnterExpressionEvaluationContext ContextRAII(
1025 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1026
1027 DeclarationName Value = S.PP.getIdentifierInfo("value");
1028 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1029
1030 // Form template argument list for tuple_size<T>.
1031 TemplateArgumentListInfo Args(Loc, Loc);
1032 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1033
1034 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1035 // it's not tuple-like.
1036 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1037 R.empty())
1038 return IsTupleLike::NotTupleLike;
1039
1040 // If we get this far, we've committed to the tuple interpretation, but
1041 // we can still fail if there actually isn't a usable ::value.
1042
1043 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1044 LookupResult &R;
1045 TemplateArgumentListInfo &Args;
1046 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1047 : R(R), Args(Args) {}
1048 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1049 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1050 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1051 }
1052 } Diagnoser(R, Args);
1053
1054 ExprResult E =
1055 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1056 if (E.isInvalid())
1057 return IsTupleLike::Error;
1058
1059 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1060 if (E.isInvalid())
1061 return IsTupleLike::Error;
1062
1063 return IsTupleLike::TupleLike;
1064}
1065
1066/// \return std::tuple_element<I, T>::type.
1067static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1068 unsigned I, QualType T) {
1069 // Form template argument list for tuple_element<I, T>.
1070 TemplateArgumentListInfo Args(Loc, Loc);
1071 Args.addArgument(
1072 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1073 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1074
1075 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1076 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1077 if (lookupStdTypeTraitMember(
1078 S, R, Loc, "tuple_element", Args,
1079 diag::err_decomp_decl_std_tuple_element_not_specialized))
1080 return QualType();
1081
1082 auto *TD = R.getAsSingle<TypeDecl>();
1083 if (!TD) {
1084 R.suppressDiagnostics();
1085 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1086 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1087 if (!R.empty())
1088 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1089 return QualType();
1090 }
1091
1092 return S.Context.getTypeDeclType(TD);
1093}
1094
1095namespace {
1096struct BindingDiagnosticTrap {
1097 Sema &S;
1098 DiagnosticErrorTrap Trap;
1099 BindingDecl *BD;
1100
1101 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1102 : S(S), Trap(S.Diags), BD(BD) {}
1103 ~BindingDiagnosticTrap() {
1104 if (Trap.hasErrorOccurred())
1105 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1106 }
1107};
1108}
1109
1110static bool checkTupleLikeDecomposition(Sema &S,
1111 ArrayRef<BindingDecl *> Bindings,
1112 VarDecl *Src, QualType DecompType,
1113 const llvm::APSInt &TupleSize) {
1114 if ((int64_t)Bindings.size() != TupleSize) {
1115 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1116 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1117 << (TupleSize < Bindings.size());
1118 return true;
1119 }
1120
1121 if (Bindings.empty())
1122 return false;
1123
1124 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1125
1126 // [dcl.decomp]p3:
1127 // The unqualified-id get is looked up in the scope of E by class member
1128 // access lookup ...
1129 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1130 bool UseMemberGet = false;
1131 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1132 if (auto *RD = DecompType->getAsCXXRecordDecl())
1133 S.LookupQualifiedName(MemberGet, RD);
1134 if (MemberGet.isAmbiguous())
1135 return true;
1136 // ... and if that finds at least one declaration that is a function
1137 // template whose first template parameter is a non-type parameter ...
1138 for (NamedDecl *D : MemberGet) {
1139 if (FunctionTemplateDecl *FTD =
1140 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1141 TemplateParameterList *TPL = FTD->getTemplateParameters();
1142 if (TPL->size() != 0 &&
1143 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1144 // ... the initializer is e.get<i>().
1145 UseMemberGet = true;
1146 break;
1147 }
1148 }
1149 }
1150 }
1151
1152 unsigned I = 0;
1153 for (auto *B : Bindings) {
1154 BindingDiagnosticTrap Trap(S, B);
1155 SourceLocation Loc = B->getLocation();
1156
1157 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1158 if (E.isInvalid())
1159 return true;
1160
1161 // e is an lvalue if the type of the entity is an lvalue reference and
1162 // an xvalue otherwise
1163 if (!Src->getType()->isLValueReferenceType())
1164 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1165 E.get(), nullptr, VK_XValue);
1166
1167 TemplateArgumentListInfo Args(Loc, Loc);
1168 Args.addArgument(
1169 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1170
1171 if (UseMemberGet) {
1172 // if [lookup of member get] finds at least one declaration, the
1173 // initializer is e.get<i-1>().
1174 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1175 CXXScopeSpec(), SourceLocation(), nullptr,
1176 MemberGet, &Args, nullptr);
1177 if (E.isInvalid())
1178 return true;
1179
1180 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1181 } else {
1182 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1183 // in the associated namespaces.
1184 Expr *Get = UnresolvedLookupExpr::Create(
1185 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1186 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1187 UnresolvedSetIterator(), UnresolvedSetIterator());
1188
1189 Expr *Arg = E.get();
1190 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1191 }
1192 if (E.isInvalid())
1193 return true;
1194 Expr *Init = E.get();
1195
1196 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1197 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1198 if (T.isNull())
1199 return true;
1200
1201 // each vi is a variable of type "reference to T" initialized with the
1202 // initializer, where the reference is an lvalue reference if the
1203 // initializer is an lvalue and an rvalue reference otherwise
1204 QualType RefType =
1205 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1206 if (RefType.isNull())
1207 return true;
1208 auto *RefVD = VarDecl::Create(
1209 S.Context, Src->getDeclContext(), Loc, Loc,
1210 B->getDeclName().getAsIdentifierInfo(), RefType,
1211 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1212 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1213 RefVD->setTSCSpec(Src->getTSCSpec());
1214 RefVD->setImplicit();
1215 if (Src->isInlineSpecified())
1216 RefVD->setInlineSpecified();
1217 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1218
1219 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1220 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1221 InitializationSequence Seq(S, Entity, Kind, Init);
1222 E = Seq.Perform(S, Entity, Kind, Init);
1223 if (E.isInvalid())
1224 return true;
1225 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1226 if (E.isInvalid())
1227 return true;
1228 RefVD->setInit(E.get());
1229 if (!E.get()->isValueDependent())
1230 RefVD->checkInitIsICE();
1231
1232 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1233 DeclarationNameInfo(B->getDeclName(), Loc),
1234 RefVD);
1235 if (E.isInvalid())
1236 return true;
1237
1238 B->setBinding(T, E.get());
1239 I++;
1240 }
1241
1242 return false;
1243}
1244
1245/// Find the base class to decompose in a built-in decomposition of a class type.
1246/// This base class search is, unfortunately, not quite like any other that we
1247/// perform anywhere else in C++.
1248static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1249 const CXXRecordDecl *RD,
1250 CXXCastPath &BasePath) {
1251 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1252 CXXBasePath &Path) {
1253 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1254 };
1255
1256 const CXXRecordDecl *ClassWithFields = nullptr;
1257 AccessSpecifier AS = AS_public;
1258 if (RD->hasDirectFields())
1259 // [dcl.decomp]p4:
1260 // Otherwise, all of E's non-static data members shall be public direct
1261 // members of E ...
1262 ClassWithFields = RD;
1263 else {
1264 // ... or of ...
1265 CXXBasePaths Paths;
1266 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1267 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1268 // If no classes have fields, just decompose RD itself. (This will work
1269 // if and only if zero bindings were provided.)
1270 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1271 }
1272
1273 CXXBasePath *BestPath = nullptr;
1274 for (auto &P : Paths) {
1275 if (!BestPath)
1276 BestPath = &P;
1277 else if (!S.Context.hasSameType(P.back().Base->getType(),
1278 BestPath->back().Base->getType())) {
1279 // ... the same ...
1280 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1281 << false << RD << BestPath->back().Base->getType()
1282 << P.back().Base->getType();
1283 return DeclAccessPair();
1284 } else if (P.Access < BestPath->Access) {
1285 BestPath = &P;
1286 }
1287 }
1288
1289 // ... unambiguous ...
1290 QualType BaseType = BestPath->back().Base->getType();
1291 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1292 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1293 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1294 return DeclAccessPair();
1295 }
1296
1297 // ... [accessible, implied by other rules] base class of E.
1298 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1299 *BestPath, diag::err_decomp_decl_inaccessible_base);
1300 AS = BestPath->Access;
1301
1302 ClassWithFields = BaseType->getAsCXXRecordDecl();
1303 S.BuildBasePathArray(Paths, BasePath);
1304 }
1305
1306 // The above search did not check whether the selected class itself has base
1307 // classes with fields, so check that now.
1308 CXXBasePaths Paths;
1309 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1310 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1311 << (ClassWithFields == RD) << RD << ClassWithFields
1312 << Paths.front().back().Base->getType();
1313 return DeclAccessPair();
1314 }
1315
1316 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1317}
1318
1319static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1320 ValueDecl *Src, QualType DecompType,
1321 const CXXRecordDecl *OrigRD) {
1322 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1323 diag::err_incomplete_type))
1324 return true;
1325
1326 CXXCastPath BasePath;
1327 DeclAccessPair BasePair =
1328 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1329 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1330 if (!RD)
1331 return true;
1332 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1333 DecompType.getQualifiers());
1334
1335 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1336 unsigned NumFields =
1337 std::count_if(RD->field_begin(), RD->field_end(),
1338 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1339 assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0)
: __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1339, __PRETTY_FUNCTION__))
;
1340 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1341 << DecompType << (unsigned)Bindings.size() << NumFields
1342 << (NumFields < Bindings.size());
1343 return true;
1344 };
1345
1346 // all of E's non-static data members shall be [...] well-formed
1347 // when named as e.name in the context of the structured binding,
1348 // E shall not have an anonymous union member, ...
1349 unsigned I = 0;
1350 for (auto *FD : RD->fields()) {
1351 if (FD->isUnnamedBitfield())
1352 continue;
1353
1354 if (FD->isAnonymousStructOrUnion()) {
1355 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1356 << DecompType << FD->getType()->isUnionType();
1357 S.Diag(FD->getLocation(), diag::note_declared_at);
1358 return true;
1359 }
1360
1361 // We have a real field to bind.
1362 if (I >= Bindings.size())
1363 return DiagnoseBadNumberOfBindings();
1364 auto *B = Bindings[I++];
1365 SourceLocation Loc = B->getLocation();
1366
1367 // The field must be accessible in the context of the structured binding.
1368 // We already checked that the base class is accessible.
1369 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1370 // const_cast here.
1371 S.CheckStructuredBindingMemberAccess(
1372 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1373 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1374 BasePair.getAccess(), FD->getAccess())));
1375
1376 // Initialize the binding to Src.FD.
1377 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1378 if (E.isInvalid())
1379 return true;
1380 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1381 VK_LValue, &BasePath);
1382 if (E.isInvalid())
1383 return true;
1384 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1385 CXXScopeSpec(), FD,
1386 DeclAccessPair::make(FD, FD->getAccess()),
1387 DeclarationNameInfo(FD->getDeclName(), Loc));
1388 if (E.isInvalid())
1389 return true;
1390
1391 // If the type of the member is T, the referenced type is cv T, where cv is
1392 // the cv-qualification of the decomposition expression.
1393 //
1394 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1395 // 'const' to the type of the field.
1396 Qualifiers Q = DecompType.getQualifiers();
1397 if (FD->isMutable())
1398 Q.removeConst();
1399 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1400 }
1401
1402 if (I != Bindings.size())
1403 return DiagnoseBadNumberOfBindings();
1404
1405 return false;
1406}
1407
1408void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1409 QualType DecompType = DD->getType();
1410
1411 // If the type of the decomposition is dependent, then so is the type of
1412 // each binding.
1413 if (DecompType->isDependentType()) {
1414 for (auto *B : DD->bindings())
1415 B->setType(Context.DependentTy);
1416 return;
1417 }
1418
1419 DecompType = DecompType.getNonReferenceType();
1420 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1421
1422 // C++1z [dcl.decomp]/2:
1423 // If E is an array type [...]
1424 // As an extension, we also support decomposition of built-in complex and
1425 // vector types.
1426 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1427 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1428 DD->setInvalidDecl();
1429 return;
1430 }
1431 if (auto *VT = DecompType->getAs<VectorType>()) {
1432 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1433 DD->setInvalidDecl();
1434 return;
1435 }
1436 if (auto *CT = DecompType->getAs<ComplexType>()) {
1437 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1438 DD->setInvalidDecl();
1439 return;
1440 }
1441
1442 // C++1z [dcl.decomp]/3:
1443 // if the expression std::tuple_size<E>::value is a well-formed integral
1444 // constant expression, [...]
1445 llvm::APSInt TupleSize(32);
1446 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1447 case IsTupleLike::Error:
1448 DD->setInvalidDecl();
1449 return;
1450
1451 case IsTupleLike::TupleLike:
1452 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1453 DD->setInvalidDecl();
1454 return;
1455
1456 case IsTupleLike::NotTupleLike:
1457 break;
1458 }
1459
1460 // C++1z [dcl.dcl]/8:
1461 // [E shall be of array or non-union class type]
1462 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1463 if (!RD || RD->isUnion()) {
1464 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1465 << DD << !RD << DecompType;
1466 DD->setInvalidDecl();
1467 return;
1468 }
1469
1470 // C++1z [dcl.decomp]/4:
1471 // all of E's non-static data members shall be [...] direct members of
1472 // E or of the same unambiguous public base class of E, ...
1473 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1474 DD->setInvalidDecl();
1475}
1476
1477/// Merge the exception specifications of two variable declarations.
1478///
1479/// This is called when there's a redeclaration of a VarDecl. The function
1480/// checks if the redeclaration might have an exception specification and
1481/// validates compatibility and merges the specs if necessary.
1482void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1483 // Shortcut if exceptions are disabled.
1484 if (!getLangOpts().CXXExceptions)
1485 return;
1486
1487 assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1488, __PRETTY_FUNCTION__))
1488 "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1488, __PRETTY_FUNCTION__))
;
1489
1490 QualType NewType = New->getType();
1491 QualType OldType = Old->getType();
1492
1493 // We're only interested in pointers and references to functions, as well
1494 // as pointers to member functions.
1495 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1496 NewType = R->getPointeeType();
1497 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1498 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1499 NewType = P->getPointeeType();
1500 OldType = OldType->getAs<PointerType>()->getPointeeType();
1501 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1502 NewType = M->getPointeeType();
1503 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1504 }
1505
1506 if (!NewType->isFunctionProtoType())
1507 return;
1508
1509 // There's lots of special cases for functions. For function pointers, system
1510 // libraries are hopefully not as broken so that we don't need these
1511 // workarounds.
1512 if (CheckEquivalentExceptionSpec(
1513 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1514 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1515 New->setInvalidDecl();
1516 }
1517}
1518
1519/// CheckCXXDefaultArguments - Verify that the default arguments for a
1520/// function declaration are well-formed according to C++
1521/// [dcl.fct.default].
1522void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1523 unsigned NumParams = FD->getNumParams();
1524 unsigned p;
1525
1526 // Find first parameter with a default argument
1527 for (p = 0; p < NumParams; ++p) {
1528 ParmVarDecl *Param = FD->getParamDecl(p);
1529 if (Param->hasDefaultArg())
1530 break;
1531 }
1532
1533 // C++11 [dcl.fct.default]p4:
1534 // In a given function declaration, each parameter subsequent to a parameter
1535 // with a default argument shall have a default argument supplied in this or
1536 // a previous declaration or shall be a function parameter pack. A default
1537 // argument shall not be redefined by a later declaration (not even to the
1538 // same value).
1539 unsigned LastMissingDefaultArg = 0;
1540 for (; p < NumParams; ++p) {
1541 ParmVarDecl *Param = FD->getParamDecl(p);
1542 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1543 if (Param->isInvalidDecl())
1544 /* We already complained about this parameter. */;
1545 else if (Param->getIdentifier())
1546 Diag(Param->getLocation(),
1547 diag::err_param_default_argument_missing_name)
1548 << Param->getIdentifier();
1549 else
1550 Diag(Param->getLocation(),
1551 diag::err_param_default_argument_missing);
1552
1553 LastMissingDefaultArg = p;
1554 }
1555 }
1556
1557 if (LastMissingDefaultArg > 0) {
1558 // Some default arguments were missing. Clear out all of the
1559 // default arguments up to (and including) the last missing
1560 // default argument, so that we leave the function parameters
1561 // in a semantically valid state.
1562 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1563 ParmVarDecl *Param = FD->getParamDecl(p);
1564 if (Param->hasDefaultArg()) {
1565 Param->setDefaultArg(nullptr);
1566 }
1567 }
1568 }
1569}
1570
1571/// Check that the given type is a literal type. Issue a diagnostic if not,
1572/// if Kind is Diagnose.
1573/// \return \c true if a problem has been found (and optionally diagnosed).
1574template <typename... Ts>
1575static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1576 SourceLocation Loc, QualType T, unsigned DiagID,
1577 Ts &&...DiagArgs) {
1578 if (T->isDependentType())
1579 return false;
1580
1581 switch (Kind) {
1582 case Sema::CheckConstexprKind::Diagnose:
1583 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1584 std::forward<Ts>(DiagArgs)...);
1585
1586 case Sema::CheckConstexprKind::CheckValid:
1587 return !T->isLiteralType(SemaRef.Context);
1588 }
1589
1590 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1590)
;
1591}
1592
1593/// Determine whether a destructor cannot be constexpr due to
1594static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1595 const CXXDestructorDecl *DD,
1596 Sema::CheckConstexprKind Kind) {
1597 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1598 const CXXRecordDecl *RD =
1599 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1600 if (!RD || RD->hasConstexprDestructor())
1601 return true;
1602
1603 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1604 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1605 << DD->getConstexprKind() << !FD
1606 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1607 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1608 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1609 }
1610 return false;
1611 };
1612
1613 const CXXRecordDecl *RD = DD->getParent();
1614 for (const CXXBaseSpecifier &B : RD->bases())
1615 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1616 return false;
1617 for (const FieldDecl *FD : RD->fields())
1618 if (!Check(FD->getLocation(), FD->getType(), FD))
1619 return false;
1620 return true;
1621}
1622
1623// CheckConstexprParameterTypes - Check whether a function's parameter types
1624// are all literal types. If so, return true. If not, produce a suitable
1625// diagnostic and return false.
1626static bool CheckConstexprParameterTypes(Sema &SemaRef,
1627 const FunctionDecl *FD,
1628 Sema::CheckConstexprKind Kind) {
1629 unsigned ArgIndex = 0;
1630 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1631 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1632 e = FT->param_type_end();
1633 i != e; ++i, ++ArgIndex) {
1634 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1635 SourceLocation ParamLoc = PD->getLocation();
1636 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1637 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1638 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1639 FD->isConsteval()))
1640 return false;
1641 }
1642 return true;
1643}
1644
1645/// Get diagnostic %select index for tag kind for
1646/// record diagnostic message.
1647/// WARNING: Indexes apply to particular diagnostics only!
1648///
1649/// \returns diagnostic %select index.
1650static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1651 switch (Tag) {
1652 case TTK_Struct: return 0;
1653 case TTK_Interface: return 1;
1654 case TTK_Class: return 2;
1655 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1655)
;
1656 }
1657}
1658
1659static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1660 Stmt *Body,
1661 Sema::CheckConstexprKind Kind);
1662
1663// Check whether a function declaration satisfies the requirements of a
1664// constexpr function definition or a constexpr constructor definition. If so,
1665// return true. If not, produce appropriate diagnostics (unless asked not to by
1666// Kind) and return false.
1667//
1668// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1669bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1670 CheckConstexprKind Kind) {
1671 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1672 if (MD && MD->isInstance()) {
1673 // C++11 [dcl.constexpr]p4:
1674 // The definition of a constexpr constructor shall satisfy the following
1675 // constraints:
1676 // - the class shall not have any virtual base classes;
1677 //
1678 // FIXME: This only applies to constructors and destructors, not arbitrary
1679 // member functions.
1680 const CXXRecordDecl *RD = MD->getParent();
1681 if (RD->getNumVBases()) {
1682 if (Kind == CheckConstexprKind::CheckValid)
1683 return false;
1684
1685 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1686 << isa<CXXConstructorDecl>(NewFD)
1687 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1688 for (const auto &I : RD->vbases())
1689 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1690 << I.getSourceRange();
1691 return false;
1692 }
1693 }
1694
1695 if (!isa<CXXConstructorDecl>(NewFD)) {
1696 // C++11 [dcl.constexpr]p3:
1697 // The definition of a constexpr function shall satisfy the following
1698 // constraints:
1699 // - it shall not be virtual; (removed in C++20)
1700 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1701 if (Method && Method->isVirtual()) {
1702 if (getLangOpts().CPlusPlus2a) {
1703 if (Kind == CheckConstexprKind::Diagnose)
1704 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1705 } else {
1706 if (Kind == CheckConstexprKind::CheckValid)
1707 return false;
1708
1709 Method = Method->getCanonicalDecl();
1710 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1711
1712 // If it's not obvious why this function is virtual, find an overridden
1713 // function which uses the 'virtual' keyword.
1714 const CXXMethodDecl *WrittenVirtual = Method;
1715 while (!WrittenVirtual->isVirtualAsWritten())
1716 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1717 if (WrittenVirtual != Method)
1718 Diag(WrittenVirtual->getLocation(),
1719 diag::note_overridden_virtual_function);
1720 return false;
1721 }
1722 }
1723
1724 // - its return type shall be a literal type;
1725 QualType RT = NewFD->getReturnType();
1726 if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
1727 diag::err_constexpr_non_literal_return,
1728 NewFD->isConsteval()))
1729 return false;
1730 }
1731
1732 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1733 // A destructor can be constexpr only if the defaulted destructor could be;
1734 // we don't need to check the members and bases if we already know they all
1735 // have constexpr destructors.
1736 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1737 if (Kind == CheckConstexprKind::CheckValid)
1738 return false;
1739 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1740 return false;
1741 }
1742 }
1743
1744 // - each of its parameter types shall be a literal type;
1745 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1746 return false;
1747
1748 Stmt *Body = NewFD->getBody();
1749 assert(Body &&((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1750, __PRETTY_FUNCTION__))
1750 "CheckConstexprFunctionDefinition called on function with no body")((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 1750, __PRETTY_FUNCTION__))
;
1751 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1752}
1753
1754/// Check the given declaration statement is legal within a constexpr function
1755/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1756///
1757/// \return true if the body is OK (maybe only as an extension), false if we
1758/// have diagnosed a problem.
1759static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1760 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1761 Sema::CheckConstexprKind Kind) {
1762 // C++11 [dcl.constexpr]p3 and p4:
1763 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1764 // contain only
1765 for (const auto *DclIt : DS->decls()) {
1766 switch (DclIt->getKind()) {
1767 case Decl::StaticAssert:
1768 case Decl::Using:
1769 case Decl::UsingShadow:
1770 case Decl::UsingDirective:
1771 case Decl::UnresolvedUsingTypename:
1772 case Decl::UnresolvedUsingValue:
1773 // - static_assert-declarations
1774 // - using-declarations,
1775 // - using-directives,
1776 continue;
1777
1778 case Decl::Typedef:
1779 case Decl::TypeAlias: {
1780 // - typedef declarations and alias-declarations that do not define
1781 // classes or enumerations,
1782 const auto *TN = cast<TypedefNameDecl>(DclIt);
1783 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1784 // Don't allow variably-modified types in constexpr functions.
1785 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1786 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1787 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1788 << TL.getSourceRange() << TL.getType()
1789 << isa<CXXConstructorDecl>(Dcl);
1790 }
1791 return false;
1792 }
1793 continue;
1794 }
1795
1796 case Decl::Enum:
1797 case Decl::CXXRecord:
1798 // C++1y allows types to be defined, not just declared.
1799 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1800 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1801 SemaRef.Diag(DS->getBeginLoc(),
1802 SemaRef.getLangOpts().CPlusPlus14
1803 ? diag::warn_cxx11_compat_constexpr_type_definition
1804 : diag::ext_constexpr_type_definition)
1805 << isa<CXXConstructorDecl>(Dcl);
1806 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1807 return false;
1808 }
1809 }
1810 continue;
1811
1812 case Decl::EnumConstant:
1813 case Decl::IndirectField:
1814 case Decl::ParmVar:
1815 // These can only appear with other declarations which are banned in
1816 // C++11 and permitted in C++1y, so ignore them.
1817 continue;
1818
1819 case Decl::Var:
1820 case Decl::Decomposition: {
1821 // C++1y [dcl.constexpr]p3 allows anything except:
1822 // a definition of a variable of non-literal type or of static or
1823 // thread storage duration or [before C++2a] for which no
1824 // initialization is performed.
1825 const auto *VD = cast<VarDecl>(DclIt);
1826 if (VD->isThisDeclarationADefinition()) {
1827 if (VD->isStaticLocal()) {
1828 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1829 SemaRef.Diag(VD->getLocation(),
1830 diag::err_constexpr_local_var_static)
1831 << isa<CXXConstructorDecl>(Dcl)
1832 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1833 }
1834 return false;
1835 }
1836 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1837 diag::err_constexpr_local_var_non_literal_type,
1838 isa<CXXConstructorDecl>(Dcl)))
1839 return false;
1840 if (!VD->getType()->isDependentType() &&
1841 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1842 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1843 SemaRef.Diag(
1844 VD->getLocation(),
1845 SemaRef.getLangOpts().CPlusPlus2a
1846 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1847 : diag::ext_constexpr_local_var_no_init)
1848 << isa<CXXConstructorDecl>(Dcl);
1849 } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
1850 return false;
1851 }
1852 continue;
1853 }
1854 }
1855 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1856 SemaRef.Diag(VD->getLocation(),
1857 SemaRef.getLangOpts().CPlusPlus14
1858 ? diag::warn_cxx11_compat_constexpr_local_var
1859 : diag::ext_constexpr_local_var)
1860 << isa<CXXConstructorDecl>(Dcl);
1861 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1862 return false;
1863 }
1864 continue;
1865 }
1866
1867 case Decl::NamespaceAlias:
1868 case Decl::Function:
1869 // These are disallowed in C++11 and permitted in C++1y. Allow them
1870 // everywhere as an extension.
1871 if (!Cxx1yLoc.isValid())
1872 Cxx1yLoc = DS->getBeginLoc();
1873 continue;
1874
1875 default:
1876 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1877 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1878 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1879 }
1880 return false;
1881 }
1882 }
1883
1884 return true;
1885}
1886
1887/// Check that the given field is initialized within a constexpr constructor.
1888///
1889/// \param Dcl The constexpr constructor being checked.
1890/// \param Field The field being checked. This may be a member of an anonymous
1891/// struct or union nested within the class being checked.
1892/// \param Inits All declarations, including anonymous struct/union members and
1893/// indirect members, for which any initialization was provided.
1894/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1895/// multiple notes for different members to the same error.
1896/// \param Kind Whether we're diagnosing a constructor as written or determining
1897/// whether the formal requirements are satisfied.
1898/// \return \c false if we're checking for validity and the constructor does
1899/// not satisfy the requirements on a constexpr constructor.
1900static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1901 const FunctionDecl *Dcl,
1902 FieldDecl *Field,
1903 llvm::SmallSet<Decl*, 16> &Inits,
1904 bool &Diagnosed,
1905 Sema::CheckConstexprKind Kind) {
1906 // In C++20 onwards, there's nothing to check for validity.
1907 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1908 SemaRef.getLangOpts().CPlusPlus2a)
1909 return true;
1910
1911 if (Field->isInvalidDecl())
1912 return true;
1913
1914 if (Field->isUnnamedBitfield())
1915 return true;
1916
1917 // Anonymous unions with no variant members and empty anonymous structs do not
1918 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1919 // indirect fields don't need initializing.
1920 if (Field->isAnonymousStructOrUnion() &&
1921 (Field->getType()->isUnionType()
1922 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1923 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1924 return true;
1925
1926 if (!Inits.count(Field)) {
1927 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1928 if (!Diagnosed) {
1929 SemaRef.Diag(Dcl->getLocation(),
1930 SemaRef.getLangOpts().CPlusPlus2a
1931 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1932 : diag::ext_constexpr_ctor_missing_init);
1933 Diagnosed = true;
1934 }
1935 SemaRef.Diag(Field->getLocation(),
1936 diag::note_constexpr_ctor_missing_init);
1937 } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
1938 return false;
1939 }
1940 } else if (Field->isAnonymousStructOrUnion()) {
1941 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1942 for (auto *I : RD->fields())
1943 // If an anonymous union contains an anonymous struct of which any member
1944 // is initialized, all members must be initialized.
1945 if (!RD->isUnion() || Inits.count(I))
1946 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1947 Kind))
1948 return false;
1949 }
1950 return true;
1951}
1952
1953/// Check the provided statement is allowed in a constexpr function
1954/// definition.
1955static bool
1956CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1957 SmallVectorImpl<SourceLocation> &ReturnStmts,
1958 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1959 Sema::CheckConstexprKind Kind) {
1960 // - its function-body shall be [...] a compound-statement that contains only
1961 switch (S->getStmtClass()) {
1962 case Stmt::NullStmtClass:
1963 // - null statements,
1964 return true;
1965
1966 case Stmt::DeclStmtClass:
1967 // - static_assert-declarations
1968 // - using-declarations,
1969 // - using-directives,
1970 // - typedef declarations and alias-declarations that do not define
1971 // classes or enumerations,
1972 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1973 return false;
1974 return true;
1975
1976 case Stmt::ReturnStmtClass:
1977 // - and exactly one return statement;
1978 if (isa<CXXConstructorDecl>(Dcl)) {
1979 // C++1y allows return statements in constexpr constructors.
1980 if (!Cxx1yLoc.isValid())
1981 Cxx1yLoc = S->getBeginLoc();
1982 return true;
1983 }
1984
1985 ReturnStmts.push_back(S->getBeginLoc());
1986 return true;
1987
1988 case Stmt::CompoundStmtClass: {
1989 // C++1y allows compound-statements.
1990 if (!Cxx1yLoc.isValid())
1991 Cxx1yLoc = S->getBeginLoc();
1992
1993 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1994 for (auto *BodyIt : CompStmt->body()) {
1995 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1996 Cxx1yLoc, Cxx2aLoc, Kind))
1997 return false;
1998 }
1999 return true;
2000 }
2001
2002 case Stmt::AttributedStmtClass:
2003 if (!Cxx1yLoc.isValid())
2004 Cxx1yLoc = S->getBeginLoc();
2005 return true;
2006
2007 case Stmt::IfStmtClass: {
2008 // C++1y allows if-statements.
2009 if (!Cxx1yLoc.isValid())
2010 Cxx1yLoc = S->getBeginLoc();
2011
2012 IfStmt *If = cast<IfStmt>(S);
2013 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2014 Cxx1yLoc, Cxx2aLoc, Kind))
2015 return false;
2016 if (If->getElse() &&
2017 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2018 Cxx1yLoc, Cxx2aLoc, Kind))
2019 return false;
2020 return true;
2021 }
2022
2023 case Stmt::WhileStmtClass:
2024 case Stmt::DoStmtClass:
2025 case Stmt::ForStmtClass:
2026 case Stmt::CXXForRangeStmtClass:
2027 case Stmt::ContinueStmtClass:
2028 // C++1y allows all of these. We don't allow them as extensions in C++11,
2029 // because they don't make sense without variable mutation.
2030 if (!SemaRef.getLangOpts().CPlusPlus14)
2031 break;
2032 if (!Cxx1yLoc.isValid())
2033 Cxx1yLoc = S->getBeginLoc();
2034 for (Stmt *SubStmt : S->children())
2035 if (SubStmt &&
2036 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2037 Cxx1yLoc, Cxx2aLoc, Kind))
2038 return false;
2039 return true;
2040
2041 case Stmt::SwitchStmtClass:
2042 case Stmt::CaseStmtClass:
2043 case Stmt::DefaultStmtClass:
2044 case Stmt::BreakStmtClass:
2045 // C++1y allows switch-statements, and since they don't need variable
2046 // mutation, we can reasonably allow them in C++11 as an extension.
2047 if (!Cxx1yLoc.isValid())
2048 Cxx1yLoc = S->getBeginLoc();
2049 for (Stmt *SubStmt : S->children())
2050 if (SubStmt &&
2051 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2052 Cxx1yLoc, Cxx2aLoc, Kind))
2053 return false;
2054 return true;
2055
2056 case Stmt::GCCAsmStmtClass:
2057 case Stmt::MSAsmStmtClass:
2058 // C++2a allows inline assembly statements.
2059 case Stmt::CXXTryStmtClass:
2060 if (Cxx2aLoc.isInvalid())
2061 Cxx2aLoc = S->getBeginLoc();
2062 for (Stmt *SubStmt : S->children()) {
2063 if (SubStmt &&
2064 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2065 Cxx1yLoc, Cxx2aLoc, Kind))
2066 return false;
2067 }
2068 return true;
2069
2070 case Stmt::CXXCatchStmtClass:
2071 // Do not bother checking the language mode (already covered by the
2072 // try block check).
2073 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2074 cast<CXXCatchStmt>(S)->getHandlerBlock(),
2075 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2076 return false;
2077 return true;
2078
2079 default:
2080 if (!isa<Expr>(S))
2081 break;
2082
2083 // C++1y allows expression-statements.
2084 if (!Cxx1yLoc.isValid())
2085 Cxx1yLoc = S->getBeginLoc();
2086 return true;
2087 }
2088
2089 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2090 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2091 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2092 }
2093 return false;
2094}
2095
2096/// Check the body for the given constexpr function declaration only contains
2097/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2098///
2099/// \return true if the body is OK, false if we have found or diagnosed a
2100/// problem.
2101static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2102 Stmt *Body,
2103 Sema::CheckConstexprKind Kind) {
2104 SmallVector<SourceLocation, 4> ReturnStmts;
2105
2106 if (isa<CXXTryStmt>(Body)) {
2107 // C++11 [dcl.constexpr]p3:
2108 // The definition of a constexpr function shall satisfy the following
2109 // constraints: [...]
2110 // - its function-body shall be = delete, = default, or a
2111 // compound-statement
2112 //
2113 // C++11 [dcl.constexpr]p4:
2114 // In the definition of a constexpr constructor, [...]
2115 // - its function-body shall not be a function-try-block;
2116 //
2117 // This restriction is lifted in C++2a, as long as inner statements also
2118 // apply the general constexpr rules.
2119 switch (Kind) {
2120 case Sema::CheckConstexprKind::CheckValid:
2121 if (!SemaRef.getLangOpts().CPlusPlus2a)
2122 return false;
2123 break;
2124
2125 case Sema::CheckConstexprKind::Diagnose:
2126 SemaRef.Diag(Body->getBeginLoc(),
2127 !SemaRef.getLangOpts().CPlusPlus2a
2128 ? diag::ext_constexpr_function_try_block_cxx2a
2129 : diag::warn_cxx17_compat_constexpr_function_try_block)
2130 << isa<CXXConstructorDecl>(Dcl);
2131 break;
2132 }
2133 }
2134
2135 // - its function-body shall be [...] a compound-statement that contains only
2136 // [... list of cases ...]
2137 //
2138 // Note that walking the children here is enough to properly check for
2139 // CompoundStmt and CXXTryStmt body.
2140 SourceLocation Cxx1yLoc, Cxx2aLoc;
2141 for (Stmt *SubStmt : Body->children()) {
2142 if (SubStmt &&
2143 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2144 Cxx1yLoc, Cxx2aLoc, Kind))
2145 return false;
2146 }
2147
2148 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2149 // If this is only valid as an extension, report that we don't satisfy the
2150 // constraints of the current language.
2151 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
2152 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2153 return false;
2154 } else if (Cxx2aLoc.isValid()) {
2155 SemaRef.Diag(Cxx2aLoc,
2156 SemaRef.getLangOpts().CPlusPlus2a
2157 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2158 : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2159 << isa<CXXConstructorDecl>(Dcl);
2160 } else if (Cxx1yLoc.isValid()) {
2161 SemaRef.Diag(Cxx1yLoc,
2162 SemaRef.getLangOpts().CPlusPlus14
2163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2164 : diag::ext_constexpr_body_invalid_stmt)
2165 << isa<CXXConstructorDecl>(Dcl);
2166 }
2167
2168 if (const CXXConstructorDecl *Constructor
2169 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2170 const CXXRecordDecl *RD = Constructor->getParent();
2171 // DR1359:
2172 // - every non-variant non-static data member and base class sub-object
2173 // shall be initialized;
2174 // DR1460:
2175 // - if the class is a union having variant members, exactly one of them
2176 // shall be initialized;
2177 if (RD->isUnion()) {
2178 if (Constructor->getNumCtorInitializers() == 0 &&
2179 RD->hasVariantMembers()) {
2180 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2181 SemaRef.Diag(
2182 Dcl->getLocation(),
2183 SemaRef.getLangOpts().CPlusPlus2a
2184 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2185 : diag::ext_constexpr_union_ctor_no_init);
2186 } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
2187 return false;
2188 }
2189 }
2190 } else if (!Constructor->isDependentContext() &&
2191 !Constructor->isDelegatingConstructor()) {
2192 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"
) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2192, __PRETTY_FUNCTION__))
;
2193
2194 // Skip detailed checking if we have enough initializers, and we would
2195 // allow at most one initializer per member.
2196 bool AnyAnonStructUnionMembers = false;
2197 unsigned Fields = 0;
2198 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2199 E = RD->field_end(); I != E; ++I, ++Fields) {
2200 if (I->isAnonymousStructOrUnion()) {
2201 AnyAnonStructUnionMembers = true;
2202 break;
2203 }
2204 }
2205 // DR1460:
2206 // - if the class is a union-like class, but is not a union, for each of
2207 // its anonymous union members having variant members, exactly one of
2208 // them shall be initialized;
2209 if (AnyAnonStructUnionMembers ||
2210 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2211 // Check initialization of non-static data members. Base classes are
2212 // always initialized so do not need to be checked. Dependent bases
2213 // might not have initializers in the member initializer list.
2214 llvm::SmallSet<Decl*, 16> Inits;
2215 for (const auto *I: Constructor->inits()) {
2216 if (FieldDecl *FD = I->getMember())
2217 Inits.insert(FD);
2218 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2219 Inits.insert(ID->chain_begin(), ID->chain_end());
2220 }
2221
2222 bool Diagnosed = false;
2223 for (auto *I : RD->fields())
2224 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2225 Kind))
2226 return false;
2227 }
2228 }
2229 } else {
2230 if (ReturnStmts.empty()) {
2231 // C++1y doesn't require constexpr functions to contain a 'return'
2232 // statement. We still do, unless the return type might be void, because
2233 // otherwise if there's no return statement, the function cannot
2234 // be used in a core constant expression.
2235 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2236 (Dcl->getReturnType()->isVoidType() ||
2237 Dcl->getReturnType()->isDependentType());
2238 switch (Kind) {
2239 case Sema::CheckConstexprKind::Diagnose:
2240 SemaRef.Diag(Dcl->getLocation(),
2241 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2242 : diag::err_constexpr_body_no_return)
2243 << Dcl->isConsteval();
2244 if (!OK)
2245 return false;
2246 break;
2247
2248 case Sema::CheckConstexprKind::CheckValid:
2249 // The formal requirements don't include this rule in C++14, even
2250 // though the "must be able to produce a constant expression" rules
2251 // still imply it in some cases.
2252 if (!SemaRef.getLangOpts().CPlusPlus14)
2253 return false;
2254 break;
2255 }
2256 } else if (ReturnStmts.size() > 1) {
2257 switch (Kind) {
2258 case Sema::CheckConstexprKind::Diagnose:
2259 SemaRef.Diag(
2260 ReturnStmts.back(),
2261 SemaRef.getLangOpts().CPlusPlus14
2262 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2263 : diag::ext_constexpr_body_multiple_return);
2264 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2265 SemaRef.Diag(ReturnStmts[I],
2266 diag::note_constexpr_body_previous_return);
2267 break;
2268
2269 case Sema::CheckConstexprKind::CheckValid:
2270 if (!SemaRef.getLangOpts().CPlusPlus14)
2271 return false;
2272 break;
2273 }
2274 }
2275 }
2276
2277 // C++11 [dcl.constexpr]p5:
2278 // if no function argument values exist such that the function invocation
2279 // substitution would produce a constant expression, the program is
2280 // ill-formed; no diagnostic required.
2281 // C++11 [dcl.constexpr]p3:
2282 // - every constructor call and implicit conversion used in initializing the
2283 // return value shall be one of those allowed in a constant expression.
2284 // C++11 [dcl.constexpr]p4:
2285 // - every constructor involved in initializing non-static data members and
2286 // base class sub-objects shall be a constexpr constructor.
2287 //
2288 // Note that this rule is distinct from the "requirements for a constexpr
2289 // function", so is not checked in CheckValid mode.
2290 SmallVector<PartialDiagnosticAt, 8> Diags;
2291 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2292 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2293 SemaRef.Diag(Dcl->getLocation(),
2294 diag::ext_constexpr_function_never_constant_expr)
2295 << isa<CXXConstructorDecl>(Dcl);
2296 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2297 SemaRef.Diag(Diags[I].first, Diags[I].second);
2298 // Don't return false here: we allow this for compatibility in
2299 // system headers.
2300 }
2301
2302 return true;
2303}
2304
2305/// Get the class that is directly named by the current context. This is the
2306/// class for which an unqualified-id in this scope could name a constructor
2307/// or destructor.
2308///
2309/// If the scope specifier denotes a class, this will be that class.
2310/// If the scope specifier is empty, this will be the class whose
2311/// member-specification we are currently within. Otherwise, there
2312/// is no such class.
2313CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2314 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2314, __PRETTY_FUNCTION__))
;
2315
2316 if (SS && SS->isInvalid())
2317 return nullptr;
2318
2319 if (SS && SS->isNotEmpty()) {
2320 DeclContext *DC = computeDeclContext(*SS, true);
2321 return dyn_cast_or_null<CXXRecordDecl>(DC);
2322 }
2323
2324 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2325}
2326
2327/// isCurrentClassName - Determine whether the identifier II is the
2328/// name of the class type currently being defined. In the case of
2329/// nested classes, this will only return true if II is the name of
2330/// the innermost class.
2331bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2332 const CXXScopeSpec *SS) {
2333 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2334 return CurDecl && &II == CurDecl->getIdentifier();
2335}
2336
2337/// Determine whether the identifier II is a typo for the name of
2338/// the class type currently being defined. If so, update it to the identifier
2339/// that should have been used.
2340bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2341 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2341, __PRETTY_FUNCTION__))
;
2342
2343 if (!getLangOpts().SpellChecking)
2344 return false;
2345
2346 CXXRecordDecl *CurDecl;
2347 if (SS && SS->isSet() && !SS->isInvalid()) {
2348 DeclContext *DC = computeDeclContext(*SS, true);
2349 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2350 } else
2351 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2352
2353 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2354 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2355 < II->getLength()) {
2356 II = CurDecl->getIdentifier();
2357 return true;
2358 }
2359
2360 return false;
2361}
2362
2363/// Determine whether the given class is a base class of the given
2364/// class, including looking at dependent bases.
2365static bool findCircularInheritance(const CXXRecordDecl *Class,
2366 const CXXRecordDecl *Current) {
2367 SmallVector<const CXXRecordDecl*, 8> Queue;
2368
2369 Class = Class->getCanonicalDecl();
2370 while (true) {
2371 for (const auto &I : Current->bases()) {
2372 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2373 if (!Base)
2374 continue;
2375
2376 Base = Base->getDefinition();
2377 if (!Base)
2378 continue;
2379
2380 if (Base->getCanonicalDecl() == Class)
2381 return true;
2382
2383 Queue.push_back(Base);
2384 }
2385
2386 if (Queue.empty())
2387 return false;
2388
2389 Current = Queue.pop_back_val();
2390 }
2391
2392 return false;
2393}
2394
2395/// Check the validity of a C++ base class specifier.
2396///
2397/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2398/// and returns NULL otherwise.
2399CXXBaseSpecifier *
2400Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2401 SourceRange SpecifierRange,
2402 bool Virtual, AccessSpecifier Access,
2403 TypeSourceInfo *TInfo,
2404 SourceLocation EllipsisLoc) {
2405 QualType BaseType = TInfo->getType();
2406
2407 // C++ [class.union]p1:
2408 // A union shall not have base classes.
2409 if (Class->isUnion()) {
7
Calling 'TagDecl::isUnion'
10
Returning from 'TagDecl::isUnion'
11
Taking false branch
2410 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2411 << SpecifierRange;
2412 return nullptr;
2413 }
2414
2415 if (EllipsisLoc.isValid() &&
13
Taking false branch
2416 !TInfo->getType()->containsUnexpandedParameterPack()) {
12
Assuming the condition is false
2417 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2418 << TInfo->getTypeLoc().getSourceRange();
2419 EllipsisLoc = SourceLocation();
2420 }
2421
2422 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2423
2424 if (BaseType->isDependentType()) {
14
Assuming the condition is false
15
Taking false branch
2425 // Make sure that we don't have circular inheritance among our dependent
2426 // bases. For non-dependent bases, the check for completeness below handles
2427 // this.
2428 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2429 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2430 ((BaseDecl = BaseDecl->getDefinition()) &&
2431 findCircularInheritance(Class, BaseDecl))) {
2432 Diag(BaseLoc, diag::err_circular_inheritance)
2433 << BaseType << Context.getTypeDeclType(Class);
2434
2435 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2436 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2437 << BaseType;
2438
2439 return nullptr;
2440 }
2441 }
2442
2443 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2444 Class->getTagKind() == TTK_Class,
2445 Access, TInfo, EllipsisLoc);
2446 }
2447
2448 // Base specifiers must be record types.
2449 if (!BaseType->isRecordType()) {
16
Calling 'Type::isRecordType'
19
Returning from 'Type::isRecordType'
20
Taking false branch
2450 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2451 return nullptr;
2452 }
2453
2454 // C++ [class.union]p1:
2455 // A union shall not be used as a base class.
2456 if (BaseType->isUnionType()) {
21
Assuming the condition is false
22
Taking false branch
2457 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2458 return nullptr;
2459 }
2460
2461 // For the MS ABI, propagate DLL attributes to base class templates.
2462 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
23
Taking false branch
2463 if (Attr *ClassAttr = getDLLAttr(Class)) {
2464 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2465 BaseType->getAsCXXRecordDecl())) {
2466 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2467 BaseLoc);
2468 }
2469 }
2470 }
2471
2472 // C++ [class.derived]p2:
2473 // The class-name in a base-specifier shall not be an incompletely
2474 // defined class.
2475 if (RequireCompleteType(BaseLoc, BaseType,
24
Assuming the condition is false
25
Taking false branch
2476 diag::err_incomplete_base_class, SpecifierRange)) {
2477 Class->setInvalidDecl();
2478 return nullptr;
2479 }
2480
2481 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2482 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
26
Assuming the object is not a 'RecordType'
27
Called C++ object pointer is null
2483 assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast
<void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2483, __PRETTY_FUNCTION__))
;
2484 BaseDecl = BaseDecl->getDefinition();
2485 assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition"
) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2485, __PRETTY_FUNCTION__))
;
2486 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2487 assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast
<void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2487, __PRETTY_FUNCTION__))
;
2488
2489 // Microsoft docs say:
2490 // "If a base-class has a code_seg attribute, derived classes must have the
2491 // same attribute."
2492 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2493 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2494 if ((DerivedCSA || BaseCSA) &&
2495 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2496 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2497 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2498 << CXXBaseDecl;
2499 return nullptr;
2500 }
2501
2502 // A class which contains a flexible array member is not suitable for use as a
2503 // base class:
2504 // - If the layout determines that a base comes before another base,
2505 // the flexible array member would index into the subsequent base.
2506 // - If the layout determines that base comes before the derived class,
2507 // the flexible array member would index into the derived class.
2508 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2509 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2510 << CXXBaseDecl->getDeclName();
2511 return nullptr;
2512 }
2513
2514 // C++ [class]p3:
2515 // If a class is marked final and it appears as a base-type-specifier in
2516 // base-clause, the program is ill-formed.
2517 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2518 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2519 << CXXBaseDecl->getDeclName()
2520 << FA->isSpelledAsSealed();
2521 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2522 << CXXBaseDecl->getDeclName() << FA->getRange();
2523 return nullptr;
2524 }
2525
2526 if (BaseDecl->isInvalidDecl())
2527 Class->setInvalidDecl();
2528
2529 // Create the base specifier.
2530 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2531 Class->getTagKind() == TTK_Class,
2532 Access, TInfo, EllipsisLoc);
2533}
2534
2535/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2536/// one entry in the base class list of a class specifier, for
2537/// example:
2538/// class foo : public bar, virtual private baz {
2539/// 'public bar' and 'virtual private baz' are each base-specifiers.
2540BaseResult
2541Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2542 ParsedAttributes &Attributes,
2543 bool Virtual, AccessSpecifier Access,
2544 ParsedType basetype, SourceLocation BaseLoc,
2545 SourceLocation EllipsisLoc) {
2546 if (!classdecl)
1
Assuming 'classdecl' is non-null
2
Taking false branch
2547 return true;
2548
2549 AdjustDeclIfTemplate(classdecl);
2550 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
3
Assuming 'classdecl' is a 'CXXRecordDecl'
2551 if (!Class
3.1
'Class' is non-null
3.1
'Class' is non-null
3.1
'Class' is non-null
)
4
Taking false branch
2552 return true;
2553
2554 // We haven't yet attached the base specifiers.
2555 Class->setIsParsingBaseSpecifiers();
2556
2557 // We do not support any C++11 attributes on base-specifiers yet.
2558 // Diagnose any attributes we see.
2559 for (const ParsedAttr &AL : Attributes) {
2560 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2561 continue;
2562 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2563 ? (unsigned)diag::warn_unknown_attribute_ignored
2564 : (unsigned)diag::err_base_specifier_attribute)
2565 << AL;
2566 }
2567
2568 TypeSourceInfo *TInfo = nullptr;
2569 GetTypeFromParser(basetype, &TInfo);
2570
2571 if (EllipsisLoc.isInvalid() &&
5
Taking false branch
2572 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2573 UPPC_BaseType))
2574 return true;
2575
2576 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
6
Calling 'Sema::CheckBaseSpecifier'
2577 Virtual, Access, TInfo,
2578 EllipsisLoc))
2579 return BaseSpec;
2580 else
2581 Class->setInvalidDecl();
2582
2583 return true;
2584}
2585
2586/// Use small set to collect indirect bases. As this is only used
2587/// locally, there's no need to abstract the small size parameter.
2588typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2589
2590/// Recursively add the bases of Type. Don't add Type itself.
2591static void
2592NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2593 const QualType &Type)
2594{
2595 // Even though the incoming type is a base, it might not be
2596 // a class -- it could be a template parm, for instance.
2597 if (auto Rec = Type->getAs<RecordType>()) {
2598 auto Decl = Rec->getAsCXXRecordDecl();
2599
2600 // Iterate over its bases.
2601 for (const auto &BaseSpec : Decl->bases()) {
2602 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2603 .getUnqualifiedType();
2604 if (Set.insert(Base).second)
2605 // If we've not already seen it, recurse.
2606 NoteIndirectBases(Context, Set, Base);
2607 }
2608 }
2609}
2610
2611/// Performs the actual work of attaching the given base class
2612/// specifiers to a C++ class.
2613bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2614 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2615 if (Bases.empty())
2616 return false;
2617
2618 // Used to keep track of which base types we have already seen, so
2619 // that we can properly diagnose redundant direct base types. Note
2620 // that the key is always the unqualified canonical type of the base
2621 // class.
2622 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2623
2624 // Used to track indirect bases so we can see if a direct base is
2625 // ambiguous.
2626 IndirectBaseSet IndirectBaseTypes;
2627
2628 // Copy non-redundant base specifiers into permanent storage.
2629 unsigned NumGoodBases = 0;
2630 bool Invalid = false;
2631 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2632 QualType NewBaseType
2633 = Context.getCanonicalType(Bases[idx]->getType());
2634 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2635
2636 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2637 if (KnownBase) {
2638 // C++ [class.mi]p3:
2639 // A class shall not be specified as a direct base class of a
2640 // derived class more than once.
2641 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2642 << KnownBase->getType() << Bases[idx]->getSourceRange();
2643
2644 // Delete the duplicate base class specifier; we're going to
2645 // overwrite its pointer later.
2646 Context.Deallocate(Bases[idx]);
2647
2648 Invalid = true;
2649 } else {
2650 // Okay, add this new base class.
2651 KnownBase = Bases[idx];
2652 Bases[NumGoodBases++] = Bases[idx];
2653
2654 // Note this base's direct & indirect bases, if there could be ambiguity.
2655 if (Bases.size() > 1)
2656 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2657
2658 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2659 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2660 if (Class->isInterface() &&
2661 (!RD->isInterfaceLike() ||
2662 KnownBase->getAccessSpecifier() != AS_public)) {
2663 // The Microsoft extension __interface does not permit bases that
2664 // are not themselves public interfaces.
2665 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2666 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2667 << RD->getSourceRange();
2668 Invalid = true;
2669 }
2670 if (RD->hasAttr<WeakAttr>())
2671 Class->addAttr(WeakAttr::CreateImplicit(Context));
2672 }
2673 }
2674 }
2675
2676 // Attach the remaining base class specifiers to the derived class.
2677 Class->setBases(Bases.data(), NumGoodBases);
2678
2679 // Check that the only base classes that are duplicate are virtual.
2680 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2681 // Check whether this direct base is inaccessible due to ambiguity.
2682 QualType BaseType = Bases[idx]->getType();
2683
2684 // Skip all dependent types in templates being used as base specifiers.
2685 // Checks below assume that the base specifier is a CXXRecord.
2686 if (BaseType->isDependentType())
2687 continue;
2688
2689 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2690 .getUnqualifiedType();
2691
2692 if (IndirectBaseTypes.count(CanonicalBase)) {
2693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2694 /*DetectVirtual=*/true);
2695 bool found
2696 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2697 assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2697, __PRETTY_FUNCTION__))
;
2698 (void)found;
2699
2700 if (Paths.isAmbiguous(CanonicalBase))
2701 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2702 << BaseType << getAmbiguousPathsDisplayString(Paths)
2703 << Bases[idx]->getSourceRange();
2704 else
2705 assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) :
__assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2705, __PRETTY_FUNCTION__))
;
2706 }
2707
2708 // Delete the base class specifier, since its data has been copied
2709 // into the CXXRecordDecl.
2710 Context.Deallocate(Bases[idx]);
2711 }
2712
2713 return Invalid;
2714}
2715
2716/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2717/// class, after checking whether there are any duplicate base
2718/// classes.
2719void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2720 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2721 if (!ClassDecl || Bases.empty())
2722 return;
2723
2724 AdjustDeclIfTemplate(ClassDecl);
2725 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2726}
2727
2728/// Determine whether the type \p Derived is a C++ class that is
2729/// derived from the type \p Base.
2730bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2731 if (!getLangOpts().CPlusPlus)
2732 return false;
2733
2734 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2735 if (!DerivedRD)
2736 return false;
2737
2738 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2739 if (!BaseRD)
2740 return false;
2741
2742 // If either the base or the derived type is invalid, don't try to
2743 // check whether one is derived from the other.
2744 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2745 return false;
2746
2747 // FIXME: In a modules build, do we need the entire path to be visible for us
2748 // to be able to use the inheritance relationship?
2749 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2750 return false;
2751
2752 return DerivedRD->isDerivedFrom(BaseRD);
2753}
2754
2755/// Determine whether the type \p Derived is a C++ class that is
2756/// derived from the type \p Base.
2757bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2758 CXXBasePaths &Paths) {
2759 if (!getLangOpts().CPlusPlus)
2760 return false;
2761
2762 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2763 if (!DerivedRD)
2764 return false;
2765
2766 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2767 if (!BaseRD)
2768 return false;
2769
2770 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2771 return false;
2772
2773 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2774}
2775
2776static void BuildBasePathArray(const CXXBasePath &Path,
2777 CXXCastPath &BasePathArray) {
2778 // We first go backward and check if we have a virtual base.
2779 // FIXME: It would be better if CXXBasePath had the base specifier for
2780 // the nearest virtual base.
2781 unsigned Start = 0;
2782 for (unsigned I = Path.size(); I != 0; --I) {
2783 if (Path[I - 1].Base->isVirtual()) {
2784 Start = I - 1;
2785 break;
2786 }
2787 }
2788
2789 // Now add all bases.
2790 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2791 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2792}
2793
2794
2795void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2796 CXXCastPath &BasePathArray) {
2797 assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!"
) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2797, __PRETTY_FUNCTION__))
;
2798 assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ?
static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2798, __PRETTY_FUNCTION__))
;
2799 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2800}
2801/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2802/// conversion (where Derived and Base are class types) is
2803/// well-formed, meaning that the conversion is unambiguous (and
2804/// that all of the base classes are accessible). Returns true
2805/// and emits a diagnostic if the code is ill-formed, returns false
2806/// otherwise. Loc is the location where this routine should point to
2807/// if there is an error, and Range is the source range to highlight
2808/// if there is an error.
2809///
2810/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2811/// diagnostic for the respective type of error will be suppressed, but the
2812/// check for ill-formed code will still be performed.
2813bool
2814Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2815 unsigned InaccessibleBaseID,
2816 unsigned AmbigiousBaseConvID,
2817 SourceLocation Loc, SourceRange Range,
2818 DeclarationName Name,
2819 CXXCastPath *BasePath,
2820 bool IgnoreAccess) {
2821 // First, determine whether the path from Derived to Base is
2822 // ambiguous. This is slightly more expensive than checking whether
2823 // the Derived to Base conversion exists, because here we need to
2824 // explore multiple paths to determine if there is an ambiguity.
2825 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2826 /*DetectVirtual=*/false);
2827 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2828 if (!DerivationOkay)
2829 return true;
2830
2831 const CXXBasePath *Path = nullptr;
2832 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2833 Path = &Paths.front();
2834
2835 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2836 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2837 // user to access such bases.
2838 if (!Path && getLangOpts().MSVCCompat) {
2839 for (const CXXBasePath &PossiblePath : Paths) {
2840 if (PossiblePath.size() == 1) {
2841 Path = &PossiblePath;
2842 if (AmbigiousBaseConvID)
2843 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2844 << Base << Derived << Range;
2845 break;
2846 }
2847 }
2848 }
2849
2850 if (Path) {
2851 if (!IgnoreAccess) {
2852 // Check that the base class can be accessed.
2853 switch (
2854 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2855 case AR_inaccessible:
2856 return true;
2857 case AR_accessible:
2858 case AR_dependent:
2859 case AR_delayed:
2860 break;
2861 }
2862 }
2863
2864 // Build a base path if necessary.
2865 if (BasePath)
2866 ::BuildBasePathArray(*Path, *BasePath);
2867 return false;
2868 }
2869
2870 if (AmbigiousBaseConvID) {
2871 // We know that the derived-to-base conversion is ambiguous, and
2872 // we're going to produce a diagnostic. Perform the derived-to-base
2873 // search just one more time to compute all of the possible paths so
2874 // that we can print them out. This is more expensive than any of
2875 // the previous derived-to-base checks we've done, but at this point
2876 // performance isn't as much of an issue.
2877 Paths.clear();
2878 Paths.setRecordingPaths(true);
2879 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2880 assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2880, __PRETTY_FUNCTION__))
;
2881 (void)StillOkay;
2882
2883 // Build up a textual representation of the ambiguous paths, e.g.,
2884 // D -> B -> A, that will be used to illustrate the ambiguous
2885 // conversions in the diagnostic. We only print one of the paths
2886 // to each base class subobject.
2887 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2888
2889 Diag(Loc, AmbigiousBaseConvID)
2890 << Derived << Base << PathDisplayStr << Range << Name;
2891 }
2892 return true;
2893}
2894
2895bool
2896Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2897 SourceLocation Loc, SourceRange Range,
2898 CXXCastPath *BasePath,
2899 bool IgnoreAccess) {
2900 return CheckDerivedToBaseConversion(
2901 Derived, Base, diag::err_upcast_to_inaccessible_base,
2902 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2903 BasePath, IgnoreAccess);
2904}
2905
2906
2907/// Builds a string representing ambiguous paths from a
2908/// specific derived class to different subobjects of the same base
2909/// class.
2910///
2911/// This function builds a string that can be used in error messages
2912/// to show the different paths that one can take through the
2913/// inheritance hierarchy to go from the derived class to different
2914/// subobjects of a base class. The result looks something like this:
2915/// @code
2916/// struct D -> struct B -> struct A
2917/// struct D -> struct C -> struct A
2918/// @endcode
2919std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2920 std::string PathDisplayStr;
2921 std::set<unsigned> DisplayedPaths;
2922 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2923 Path != Paths.end(); ++Path) {
2924 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2925 // We haven't displayed a path to this particular base
2926 // class subobject yet.
2927 PathDisplayStr += "\n ";
2928 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2929 for (CXXBasePath::const_iterator Element = Path->begin();
2930 Element != Path->end(); ++Element)
2931 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2932 }
2933 }
2934
2935 return PathDisplayStr;
2936}
2937
2938//===----------------------------------------------------------------------===//
2939// C++ class member Handling
2940//===----------------------------------------------------------------------===//
2941
2942/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2943bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2944 SourceLocation ColonLoc,
2945 const ParsedAttributesView &Attrs) {
2946 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 2946, __PRETTY_FUNCTION__))
;
2947 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2948 ASLoc, ColonLoc);
2949 CurContext->addHiddenDecl(ASDecl);
2950 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2951}
2952
2953/// CheckOverrideControl - Check C++11 override control semantics.
2954void Sema::CheckOverrideControl(NamedDecl *D) {
2955 if (D->isInvalidDecl())
2956 return;
2957
2958 // We only care about "override" and "final" declarations.
2959 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2960 return;
2961
2962 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2963
2964 // We can't check dependent instance methods.
2965 if (MD && MD->isInstance() &&
2966 (MD->getParent()->hasAnyDependentBases() ||
2967 MD->getType()->isDependentType()))
2968 return;
2969
2970 if (MD && !MD->isVirtual()) {
2971 // If we have a non-virtual method, check if if hides a virtual method.
2972 // (In that case, it's most likely the method has the wrong type.)
2973 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2974 FindHiddenVirtualMethods(MD, OverloadedMethods);
2975
2976 if (!OverloadedMethods.empty()) {
2977 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2978 Diag(OA->getLocation(),
2979 diag::override_keyword_hides_virtual_member_function)
2980 << "override" << (OverloadedMethods.size() > 1);
2981 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2982 Diag(FA->getLocation(),
2983 diag::override_keyword_hides_virtual_member_function)
2984 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2985 << (OverloadedMethods.size() > 1);
2986 }
2987 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2988 MD->setInvalidDecl();
2989 return;
2990 }
2991 // Fall through into the general case diagnostic.
2992 // FIXME: We might want to attempt typo correction here.
2993 }
2994
2995 if (!MD || !MD->isVirtual()) {
2996 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2997 Diag(OA->getLocation(),
2998 diag::override_keyword_only_allowed_on_virtual_member_functions)
2999 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3000 D->dropAttr<OverrideAttr>();
3001 }
3002 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3003 Diag(FA->getLocation(),
3004 diag::override_keyword_only_allowed_on_virtual_member_functions)
3005 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3006 << FixItHint::CreateRemoval(FA->getLocation());
3007 D->dropAttr<FinalAttr>();
3008 }
3009 return;
3010 }
3011
3012 // C++11 [class.virtual]p5:
3013 // If a function is marked with the virt-specifier override and
3014 // does not override a member function of a base class, the program is
3015 // ill-formed.
3016 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3017 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3018 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3019 << MD->getDeclName();
3020}
3021
3022void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
3023 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3024 return;
3025 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3026 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3027 return;
3028
3029 SourceLocation Loc = MD->getLocation();
3030 SourceLocation SpellingLoc = Loc;
3031 if (getSourceManager().isMacroArgExpansion(Loc))
3032 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3033 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3034 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3035 return;
3036
3037 if (MD->size_overridden_methods() > 0) {
3038 unsigned DiagID = isa<CXXDestructorDecl>(MD)
3039 ? diag::warn_destructor_marked_not_override_overriding
3040 : diag::warn_function_marked_not_override_overriding;
3041 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3042 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3043 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3044 }
3045}
3046
3047/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3048/// function overrides a virtual member function marked 'final', according to
3049/// C++11 [class.virtual]p4.
3050bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3051 const CXXMethodDecl *Old) {
3052 FinalAttr *FA = Old->getAttr<FinalAttr>();
3053 if (!FA)
3054 return false;
3055
3056 Diag(New->getLocation(), diag::err_final_function_overridden)
3057 << New->getDeclName()
3058 << FA->isSpelledAsSealed();
3059 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3060 return true;
3061}
3062
3063static bool InitializationHasSideEffects(const FieldDecl &FD) {
3064 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3065 // FIXME: Destruction of ObjC lifetime types has side-effects.
3066 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3067 return !RD->isCompleteDefinition() ||
3068 !RD->hasTrivialDefaultConstructor() ||
3069 !RD->hasTrivialDestructor();
3070 return false;
3071}
3072
3073static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3074 ParsedAttributesView::const_iterator Itr =
3075 llvm::find_if(list, [](const ParsedAttr &AL) {
3076 return AL.isDeclspecPropertyAttribute();
3077 });
3078 if (Itr != list.end())
3079 return &*Itr;
3080 return nullptr;
3081}
3082
3083// Check if there is a field shadowing.
3084void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3085 DeclarationName FieldName,
3086 const CXXRecordDecl *RD,
3087 bool DeclIsField) {
3088 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3089 return;
3090
3091 // To record a shadowed field in a base
3092 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3093 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3094 CXXBasePath &Path) {
3095 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3096 // Record an ambiguous path directly
3097 if (Bases.find(Base) != Bases.end())
3098 return true;
3099 for (const auto Field : Base->lookup(FieldName)) {
3100 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3101 Field->getAccess() != AS_private) {
3102 assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void>
(0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3102, __PRETTY_FUNCTION__))
;
3103 assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> (
0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3103, __PRETTY_FUNCTION__))
;
3104 Bases[Base] = Field;
3105 return true;
3106 }
3107 }
3108 return false;
3109 };
3110
3111 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3112 /*DetectVirtual=*/true);
3113 if (!RD->lookupInBases(FieldShadowed, Paths))
3114 return;
3115
3116 for (const auto &P : Paths) {
3117 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3118 auto It = Bases.find(Base);
3119 // Skip duplicated bases
3120 if (It == Bases.end())
3121 continue;
3122 auto BaseField = It->second;
3123 assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void
> (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3123, __PRETTY_FUNCTION__))
;
3124 if (AS_none !=
3125 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3126 Diag(Loc, diag::warn_shadow_field)
3127 << FieldName << RD << Base << DeclIsField;
3128 Diag(BaseField->getLocation(), diag::note_shadow_field);
3129 Bases.erase(It);
3130 }
3131 }
3132}
3133
3134/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3135/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3136/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3137/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3138/// present (but parsing it has been deferred).
3139NamedDecl *
3140Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3141 MultiTemplateParamsArg TemplateParameterLists,
3142 Expr *BW, const VirtSpecifiers &VS,
3143 InClassInitStyle InitStyle) {
3144 const DeclSpec &DS = D.getDeclSpec();
3145 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3146 DeclarationName Name = NameInfo.getName();
3147 SourceLocation Loc = NameInfo.getLoc();
3148
3149 // For anonymous bitfields, the location should point to the type.
3150 if (Loc.isInvalid())
3151 Loc = D.getBeginLoc();
3152
3153 Expr *BitWidth = static_cast<Expr*>(BW);
3154
3155 assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void
> (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3155, __PRETTY_FUNCTION__))
;
3156 assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3156, __PRETTY_FUNCTION__))
;
3157
3158 bool isFunc = D.isDeclarationOfFunction();
3159 const ParsedAttr *MSPropertyAttr =
3160 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3161
3162 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3163 // The Microsoft extension __interface only permits public member functions
3164 // and prohibits constructors, destructors, operators, non-public member
3165 // functions, static methods and data members.
3166 unsigned InvalidDecl;
3167 bool ShowDeclName = true;
3168 if (!isFunc &&
3169 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3170 InvalidDecl = 0;
3171 else if (!isFunc)
3172 InvalidDecl = 1;
3173 else if (AS != AS_public)
3174 InvalidDecl = 2;
3175 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3176 InvalidDecl = 3;
3177 else switch (Name.getNameKind()) {
3178 case DeclarationName::CXXConstructorName:
3179 InvalidDecl = 4;
3180 ShowDeclName = false;
3181 break;
3182
3183 case DeclarationName::CXXDestructorName:
3184 InvalidDecl = 5;
3185 ShowDeclName = false;
3186 break;
3187
3188 case DeclarationName::CXXOperatorName:
3189 case DeclarationName::CXXConversionFunctionName:
3190 InvalidDecl = 6;
3191 break;
3192
3193 default:
3194 InvalidDecl = 0;
3195 break;
3196 }
3197
3198 if (InvalidDecl) {
3199 if (ShowDeclName)
3200 Diag(Loc, diag::err_invalid_member_in_interface)
3201 << (InvalidDecl-1) << Name;
3202 else
3203 Diag(Loc, diag::err_invalid_member_in_interface)
3204 << (InvalidDecl-1) << "";
3205 return nullptr;
3206 }
3207 }
3208
3209 // C++ 9.2p6: A member shall not be declared to have automatic storage
3210 // duration (auto, register) or with the extern storage-class-specifier.
3211 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3212 // data members and cannot be applied to names declared const or static,
3213 // and cannot be applied to reference members.
3214 switch (DS.getStorageClassSpec()) {
3215 case DeclSpec::SCS_unspecified:
3216 case DeclSpec::SCS_typedef:
3217 case DeclSpec::SCS_static:
3218 break;
3219 case DeclSpec::SCS_mutable:
3220 if (isFunc) {
3221 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3222
3223 // FIXME: It would be nicer if the keyword was ignored only for this
3224 // declarator. Otherwise we could get follow-up errors.
3225 D.getMutableDeclSpec().ClearStorageClassSpecs();
3226 }
3227 break;
3228 default:
3229 Diag(DS.getStorageClassSpecLoc(),
3230 diag::err_storageclass_invalid_for_member);
3231 D.getMutableDeclSpec().ClearStorageClassSpecs();
3232 break;
3233 }
3234
3235 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3236 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3237 !isFunc);
3238
3239 if (DS.hasConstexprSpecifier() && isInstField) {
3240 SemaDiagnosticBuilder B =
3241 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3242 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3243 if (InitStyle == ICIS_NoInit) {
3244 B << 0 << 0;
3245 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3246 B << FixItHint::CreateRemoval(ConstexprLoc);
3247 else {
3248 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3249 D.getMutableDeclSpec().ClearConstexprSpec();
3250 const char *PrevSpec;
3251 unsigned DiagID;
3252 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3253 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3254 (void)Failed;
3255 assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail"
) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3255, __PRETTY_FUNCTION__))
;
3256 }
3257 } else {
3258 B << 1;
3259 const char *PrevSpec;
3260 unsigned DiagID;
3261 if (D.getMutableDeclSpec().SetStorageClassSpec(
3262 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3263 Context.getPrintingPolicy())) {
3264 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3265, __PRETTY_FUNCTION__))
3265 "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3265, __PRETTY_FUNCTION__))
;
3266 B << 1;
3267 } else {
3268 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3269 isInstField = false;
3270 }
3271 }
3272 }
3273
3274 NamedDecl *Member;
3275 if (isInstField) {
3276 CXXScopeSpec &SS = D.getCXXScopeSpec();
3277
3278 // Data members must have identifiers for names.
3279 if (!Name.isIdentifier()) {
3280 Diag(Loc, diag::err_bad_variable_name)
3281 << Name;
3282 return nullptr;
3283 }
3284
3285 IdentifierInfo *II = Name.getAsIdentifierInfo();
3286
3287 // Member field could not be with "template" keyword.
3288 // So TemplateParameterLists should be empty in this case.
3289 if (TemplateParameterLists.size()) {
3290 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3291 if (TemplateParams->size()) {
3292 // There is no such thing as a member field template.
3293 Diag(D.getIdentifierLoc(), diag::err_template_member)
3294 << II
3295 << SourceRange(TemplateParams->getTemplateLoc(),
3296 TemplateParams->getRAngleLoc());
3297 } else {
3298 // There is an extraneous 'template<>' for this member.
3299 Diag(TemplateParams->getTemplateLoc(),
3300 diag::err_template_member_noparams)
3301 << II
3302 << SourceRange(TemplateParams->getTemplateLoc(),
3303 TemplateParams->getRAngleLoc());
3304 }
3305 return nullptr;
3306 }
3307
3308 if (SS.isSet() && !SS.isInvalid()) {
3309 // The user provided a superfluous scope specifier inside a class
3310 // definition:
3311 //
3312 // class X {
3313 // int X::member;
3314 // };
3315 if (DeclContext *DC = computeDeclContext(SS, false))
3316 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3317 D.getName().getKind() ==
3318 UnqualifiedIdKind::IK_TemplateId);
3319 else
3320 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3321 << Name << SS.getRange();
3322
3323 SS.clear();
3324 }
3325
3326 if (MSPropertyAttr) {
3327 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3328 BitWidth, InitStyle, AS, *MSPropertyAttr);
3329 if (!Member)
3330 return nullptr;
3331 isInstField = false;
3332 } else {
3333 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3334 BitWidth, InitStyle, AS);
3335 if (!Member)
3336 return nullptr;
3337 }
3338
3339 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3340 } else {
3341 Member = HandleDeclarator(S, D, TemplateParameterLists);
3342 if (!Member)
3343 return nullptr;
3344
3345 // Non-instance-fields can't have a bitfield.
3346 if (BitWidth) {
3347 if (Member->isInvalidDecl()) {
3348 // don't emit another diagnostic.
3349 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3350 // C++ 9.6p3: A bit-field shall not be a static member.
3351 // "static member 'A' cannot be a bit-field"
3352 Diag(Loc, diag::err_static_not_bitfield)
3353 << Name << BitWidth->getSourceRange();
3354 } else if (isa<TypedefDecl>(Member)) {
3355 // "typedef member 'x' cannot be a bit-field"
3356 Diag(Loc, diag::err_typedef_not_bitfield)
3357 << Name << BitWidth->getSourceRange();
3358 } else {
3359 // A function typedef ("typedef int f(); f a;").
3360 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3361 Diag(Loc, diag::err_not_integral_type_bitfield)
3362 << Name << cast<ValueDecl>(Member)->getType()
3363 << BitWidth->getSourceRange();
3364 }
3365
3366 BitWidth = nullptr;
3367 Member->setInvalidDecl();
3368 }
3369
3370 NamedDecl *NonTemplateMember = Member;
3371 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3372 NonTemplateMember = FunTmpl->getTemplatedDecl();
3373 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3374 NonTemplateMember = VarTmpl->getTemplatedDecl();
3375
3376 Member->setAccess(AS);
3377
3378 // If we have declared a member function template or static data member
3379 // template, set the access of the templated declaration as well.
3380 if (NonTemplateMember != Member)
3381 NonTemplateMember->setAccess(AS);
3382
3383 // C++ [temp.deduct.guide]p3:
3384 // A deduction guide [...] for a member class template [shall be
3385 // declared] with the same access [as the template].
3386 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3387 auto *TD = DG->getDeducedTemplate();
3388 // Access specifiers are only meaningful if both the template and the
3389 // deduction guide are from the same scope.
3390 if (AS != TD->getAccess() &&
3391 TD->getDeclContext()->getRedeclContext()->Equals(
3392 DG->getDeclContext()->getRedeclContext())) {
3393 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3394 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3395 << TD->getAccess();
3396 const AccessSpecDecl *LastAccessSpec = nullptr;
3397 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3398 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3399 LastAccessSpec = AccessSpec;
3400 }
3401 assert(LastAccessSpec && "differing access with no access specifier")((LastAccessSpec && "differing access with no access specifier"
) ? static_cast<void> (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3401, __PRETTY_FUNCTION__))
;
3402 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3403 << AS;
3404 }
3405 }
3406 }
3407
3408 if (VS.isOverrideSpecified())
3409 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3410 AttributeCommonInfo::AS_Keyword));
3411 if (VS.isFinalSpecified())
3412 Member->addAttr(FinalAttr::Create(
3413 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3414 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3415
3416 if (VS.getLastLocation().isValid()) {
3417 // Update the end location of a method that has a virt-specifiers.
3418 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3419 MD->setRangeEnd(VS.getLastLocation());
3420 }
3421
3422 CheckOverrideControl(Member);
3423
3424 assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?"
) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3424, __PRETTY_FUNCTION__))
;
3425
3426 if (isInstField) {
3427 FieldDecl *FD = cast<FieldDecl>(Member);
3428 FieldCollector->Add(FD);
3429
3430 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3431 // Remember all explicit private FieldDecls that have a name, no side
3432 // effects and are not part of a dependent type declaration.
3433 if (!FD->isImplicit() && FD->getDeclName() &&
3434 FD->getAccess() == AS_private &&
3435 !FD->hasAttr<UnusedAttr>() &&
3436 !FD->getParent()->isDependentContext() &&
3437 !InitializationHasSideEffects(*FD))
3438 UnusedPrivateFields.insert(FD);
3439 }
3440 }
3441
3442 return Member;
3443}
3444
3445namespace {
3446 class UninitializedFieldVisitor
3447 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3448 Sema &S;
3449 // List of Decls to generate a warning on. Also remove Decls that become
3450 // initialized.
3451 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3452 // List of base classes of the record. Classes are removed after their
3453 // initializers.
3454 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3455 // Vector of decls to be removed from the Decl set prior to visiting the
3456 // nodes. These Decls may have been initialized in the prior initializer.
3457 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3458 // If non-null, add a note to the warning pointing back to the constructor.
3459 const CXXConstructorDecl *Constructor;
3460 // Variables to hold state when processing an initializer list. When
3461 // InitList is true, special case initialization of FieldDecls matching
3462 // InitListFieldDecl.
3463 bool InitList;
3464 FieldDecl *InitListFieldDecl;
3465 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3466
3467 public:
3468 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3469 UninitializedFieldVisitor(Sema &S,
3470 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3471 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3472 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3473 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3474
3475 // Returns true if the use of ME is not an uninitialized use.
3476 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3477 bool CheckReferenceOnly) {
3478 llvm::SmallVector<FieldDecl*, 4> Fields;
3479 bool ReferenceField = false;
3480 while (ME) {
3481 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3482 if (!FD)
3483 return false;
3484 Fields.push_back(FD);
3485 if (FD->getType()->isReferenceType())
3486 ReferenceField = true;
3487 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3488 }
3489
3490 // Binding a reference to an uninitialized field is not an
3491 // uninitialized use.
3492 if (CheckReferenceOnly && !ReferenceField)
3493 return true;
3494
3495 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3496 // Discard the first field since it is the field decl that is being
3497 // initialized.
3498 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3499 UsedFieldIndex.push_back((*I)->getFieldIndex());
3500 }
3501
3502 for (auto UsedIter = UsedFieldIndex.begin(),
3503 UsedEnd = UsedFieldIndex.end(),
3504 OrigIter = InitFieldIndex.begin(),
3505 OrigEnd = InitFieldIndex.end();
3506 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3507 if (*UsedIter < *OrigIter)
3508 return true;
3509 if (*UsedIter > *OrigIter)
3510 break;
3511 }
3512
3513 return false;
3514 }
3515
3516 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3517 bool AddressOf) {
3518 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3519 return;
3520
3521 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3522 // or union.
3523 MemberExpr *FieldME = ME;
3524
3525 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3526
3527 Expr *Base = ME;
3528 while (MemberExpr *SubME =
3529 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3530
3531 if (isa<VarDecl>(SubME->getMemberDecl()))
3532 return;
3533
3534 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3535 if (!FD->isAnonymousStructOrUnion())
3536 FieldME = SubME;
3537
3538 if (!FieldME->getType().isPODType(S.Context))
3539 AllPODFields = false;
3540
3541 Base = SubME->getBase();
3542 }
3543
3544 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3545 return;
3546
3547 if (AddressOf && AllPODFields)
3548 return;
3549
3550 ValueDecl* FoundVD = FieldME->getMemberDecl();
3551
3552 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3553 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3554 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3555 }
3556
3557 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3558 QualType T = BaseCast->getType();
3559 if (T->isPointerType() &&
3560 BaseClasses.count(T->getPointeeType())) {
3561 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3562 << T->getPointeeType() << FoundVD;
3563 }
3564 }
3565 }
3566
3567 if (!Decls.count(FoundVD))
3568 return;
3569
3570 const bool IsReference = FoundVD->getType()->isReferenceType();
3571
3572 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3573 // Special checking for initializer lists.
3574 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3575 return;
3576 }
3577 } else {
3578 // Prevent double warnings on use of unbounded references.
3579 if (CheckReferenceOnly && !IsReference)
3580 return;
3581 }
3582
3583 unsigned diag = IsReference
3584 ? diag::warn_reference_field_is_uninit
3585 : diag::warn_field_is_uninit;
3586 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3587 if (Constructor)
3588 S.Diag(Constructor->getLocation(),
3589 diag::note_uninit_in_this_constructor)
3590 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3591
3592 }
3593
3594 void HandleValue(Expr *E, bool AddressOf) {
3595 E = E->IgnoreParens();
3596
3597 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3598 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3599 AddressOf /*AddressOf*/);
3600 return;
3601 }
3602
3603 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3604 Visit(CO->getCond());
3605 HandleValue(CO->getTrueExpr(), AddressOf);
3606 HandleValue(CO->getFalseExpr(), AddressOf);
3607 return;
3608 }
3609
3610 if (BinaryConditionalOperator *BCO =
3611 dyn_cast<BinaryConditionalOperator>(E)) {
3612 Visit(BCO->getCond());
3613 HandleValue(BCO->getFalseExpr(), AddressOf);
3614 return;
3615 }
3616
3617 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3618 HandleValue(OVE->getSourceExpr(), AddressOf);
3619 return;
3620 }
3621
3622 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3623 switch (BO->getOpcode()) {
3624 default:
3625 break;
3626 case(BO_PtrMemD):
3627 case(BO_PtrMemI):
3628 HandleValue(BO->getLHS(), AddressOf);
3629 Visit(BO->getRHS());
3630 return;
3631 case(BO_Comma):
3632 Visit(BO->getLHS());
3633 HandleValue(BO->getRHS(), AddressOf);
3634 return;
3635 }
3636 }
3637
3638 Visit(E);
3639 }
3640
3641 void CheckInitListExpr(InitListExpr *ILE) {
3642 InitFieldIndex.push_back(0);
3643 for (auto Child : ILE->children()) {
3644 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3645 CheckInitListExpr(SubList);
3646 } else {
3647 Visit(Child);
3648 }
3649 ++InitFieldIndex.back();
3650 }
3651 InitFieldIndex.pop_back();
3652 }
3653
3654 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3655 FieldDecl *Field, const Type *BaseClass) {
3656 // Remove Decls that may have been initialized in the previous
3657 // initializer.
3658 for (ValueDecl* VD : DeclsToRemove)
3659 Decls.erase(VD);
3660 DeclsToRemove.clear();
3661
3662 Constructor = FieldConstructor;
3663 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3664
3665 if (ILE && Field) {
3666 InitList = true;
3667 InitListFieldDecl = Field;
3668 InitFieldIndex.clear();
3669 CheckInitListExpr(ILE);
3670 } else {
3671 InitList = false;
3672 Visit(E);
3673 }
3674
3675 if (Field)
3676 Decls.erase(Field);
3677 if (BaseClass)
3678 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3679 }
3680
3681 void VisitMemberExpr(MemberExpr *ME) {
3682 // All uses of unbounded reference fields will warn.
3683 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3684 }
3685
3686 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3687 if (E->getCastKind() == CK_LValueToRValue) {
3688 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3689 return;
3690 }
3691
3692 Inherited::VisitImplicitCastExpr(E);
3693 }
3694
3695 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3696 if (E->getConstructor()->isCopyConstructor()) {
3697 Expr *ArgExpr = E->getArg(0);
3698 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3699 if (ILE->getNumInits() == 1)
3700 ArgExpr = ILE->getInit(0);
3701 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3702 if (ICE->getCastKind() == CK_NoOp)
3703 ArgExpr = ICE->getSubExpr();
3704 HandleValue(ArgExpr, false /*AddressOf*/);
3705 return;
3706 }
3707 Inherited::VisitCXXConstructExpr(E);
3708 }
3709
3710 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3711 Expr *Callee = E->getCallee();
3712 if (isa<MemberExpr>(Callee)) {
3713 HandleValue(Callee, false /*AddressOf*/);
3714 for (auto Arg : E->arguments())
3715 Visit(Arg);
3716 return;
3717 }
3718
3719 Inherited::VisitCXXMemberCallExpr(E);
3720 }
3721
3722 void VisitCallExpr(CallExpr *E) {
3723 // Treat std::move as a use.
3724 if (E->isCallToStdMove()) {
3725 HandleValue(E->getArg(0), /*AddressOf=*/false);
3726 return;
3727 }
3728
3729 Inherited::VisitCallExpr(E);
3730 }
3731
3732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3733 Expr *Callee = E->getCallee();
3734
3735 if (isa<UnresolvedLookupExpr>(Callee))
3736 return Inherited::VisitCXXOperatorCallExpr(E);
3737
3738 Visit(Callee);
3739 for (auto Arg : E->arguments())
3740 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3741 }
3742
3743 void VisitBinaryOperator(BinaryOperator *E) {
3744 // If a field assignment is detected, remove the field from the
3745 // uninitiailized field set.
3746 if (E->getOpcode() == BO_Assign)
3747 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3748 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3749 if (!FD->getType()->isReferenceType())
3750 DeclsToRemove.push_back(FD);
3751
3752 if (E->isCompoundAssignmentOp()) {
3753 HandleValue(E->getLHS(), false /*AddressOf*/);
3754 Visit(E->getRHS());
3755 return;
3756 }
3757
3758 Inherited::VisitBinaryOperator(E);
3759 }
3760
3761 void VisitUnaryOperator(UnaryOperator *E) {
3762 if (E->isIncrementDecrementOp()) {
3763 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3764 return;
3765 }
3766 if (E->getOpcode() == UO_AddrOf) {
3767 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3768 HandleValue(ME->getBase(), true /*AddressOf*/);
3769 return;
3770 }
3771 }
3772
3773 Inherited::VisitUnaryOperator(E);
3774 }
3775 };
3776
3777 // Diagnose value-uses of fields to initialize themselves, e.g.
3778 // foo(foo)
3779 // where foo is not also a parameter to the constructor.
3780 // Also diagnose across field uninitialized use such as
3781 // x(y), y(x)
3782 // TODO: implement -Wuninitialized and fold this into that framework.
3783 static void DiagnoseUninitializedFields(
3784 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3785
3786 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3787 Constructor->getLocation())) {
3788 return;
3789 }
3790
3791 if (Constructor->isInvalidDecl())
3792 return;
3793
3794 const CXXRecordDecl *RD = Constructor->getParent();
3795
3796 if (RD->getDescribedClassTemplate())
3797 return;
3798
3799 // Holds fields that are uninitialized.
3800 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3801
3802 // At the beginning, all fields are uninitialized.
3803 for (auto *I : RD->decls()) {
3804 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3805 UninitializedFields.insert(FD);
3806 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3807 UninitializedFields.insert(IFD->getAnonField());
3808 }
3809 }
3810
3811 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3812 for (auto I : RD->bases())
3813 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3814
3815 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3816 return;
3817
3818 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3819 UninitializedFields,
3820 UninitializedBaseClasses);
3821
3822 for (const auto *FieldInit : Constructor->inits()) {
3823 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3824 break;
3825
3826 Expr *InitExpr = FieldInit->getInit();
3827 if (!InitExpr)
3828 continue;
3829
3830 if (CXXDefaultInitExpr *Default =
3831 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3832 InitExpr = Default->getExpr();
3833 if (!InitExpr)
3834 continue;
3835 // In class initializers will point to the constructor.
3836 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3837 FieldInit->getAnyMember(),
3838 FieldInit->getBaseClass());
3839 } else {
3840 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3841 FieldInit->getAnyMember(),
3842 FieldInit->getBaseClass());
3843 }
3844 }
3845 }
3846} // namespace
3847
3848/// Enter a new C++ default initializer scope. After calling this, the
3849/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3850/// parsing or instantiating the initializer failed.
3851void Sema::ActOnStartCXXInClassMemberInitializer() {
3852 // Create a synthetic function scope to represent the call to the constructor
3853 // that notionally surrounds a use of this initializer.
3854 PushFunctionScope();
3855}
3856
3857/// This is invoked after parsing an in-class initializer for a
3858/// non-static C++ class member, and after instantiating an in-class initializer
3859/// in a class template. Such actions are deferred until the class is complete.
3860void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3861 SourceLocation InitLoc,
3862 Expr *InitExpr) {
3863 // Pop the notional constructor scope we created earlier.
3864 PopFunctionScopeInfo(nullptr, D);
3865
3866 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3867 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3868, __PRETTY_FUNCTION__))
3868 "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 3868, __PRETTY_FUNCTION__))
;
3869
3870 if (!InitExpr) {
3871 D->setInvalidDecl();
3872 if (FD)
3873 FD->removeInClassInitializer();
3874 return;
3875 }
3876
3877 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3878 FD->setInvalidDecl();
3879 FD->removeInClassInitializer();
3880 return;
3881 }
3882
3883 ExprResult Init = InitExpr;
3884 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3885 InitializedEntity Entity =
3886 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3887 InitializationKind Kind =
3888 FD->getInClassInitStyle() == ICIS_ListInit
3889 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3890 InitExpr->getBeginLoc(),
3891 InitExpr->getEndLoc())
3892 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3893 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3894 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3895 if (Init.isInvalid()) {
3896 FD->setInvalidDecl();
3897 return;
3898 }
3899 }
3900
3901 // C++11 [class.base.init]p7:
3902 // The initialization of each base and member constitutes a
3903 // full-expression.
3904 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3905 if (Init.isInvalid()) {
3906 FD->setInvalidDecl();
3907 return;
3908 }
3909
3910 InitExpr = Init.get();
3911
3912 FD->setInClassInitializer(InitExpr);
3913}
3914
3915/// Find the direct and/or virtual base specifiers that
3916/// correspond to the given base type, for use in base initialization
3917/// within a constructor.
3918static bool FindBaseInitializer(Sema &SemaRef,
3919 CXXRecordDecl *ClassDecl,
3920 QualType BaseType,
3921 const CXXBaseSpecifier *&DirectBaseSpec,
3922 const CXXBaseSpecifier *&VirtualBaseSpec) {
3923 // First, check for a direct base class.
3924 DirectBaseSpec = nullptr;
3925 for (const auto &Base : ClassDecl->bases()) {
3926 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3927 // We found a direct base of this type. That's what we're
3928 // initializing.
3929 DirectBaseSpec = &Base;
3930 break;
3931 }
3932 }
3933
3934 // Check for a virtual base class.
3935 // FIXME: We might be able to short-circuit this if we know in advance that
3936 // there are no virtual bases.
3937 VirtualBaseSpec = nullptr;
3938 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3939 // We haven't found a base yet; search the class hierarchy for a
3940 // virtual base class.
3941 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3942 /*DetectVirtual=*/false);
3943 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3944 SemaRef.Context.getTypeDeclType(ClassDecl),
3945 BaseType, Paths)) {
3946 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3947 Path != Paths.end(); ++Path) {
3948 if (Path->back().Base->isVirtual()) {
3949 VirtualBaseSpec = Path->back().Base;
3950 break;
3951 }
3952 }
3953 }
3954 }
3955
3956 return DirectBaseSpec || VirtualBaseSpec;
3957}
3958
3959/// Handle a C++ member initializer using braced-init-list syntax.
3960MemInitResult
3961Sema::ActOnMemInitializer(Decl *ConstructorD,
3962 Scope *S,
3963 CXXScopeSpec &SS,
3964 IdentifierInfo *MemberOrBase,
3965 ParsedType TemplateTypeTy,
3966 const DeclSpec &DS,
3967 SourceLocation IdLoc,
3968 Expr *InitList,
3969 SourceLocation EllipsisLoc) {
3970 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3971 DS, IdLoc, InitList,
3972 EllipsisLoc);
3973}
3974
3975/// Handle a C++ member initializer using parentheses syntax.
3976MemInitResult
3977Sema::ActOnMemInitializer(Decl *ConstructorD,
3978 Scope *S,
3979 CXXScopeSpec &SS,
3980 IdentifierInfo *MemberOrBase,
3981 ParsedType TemplateTypeTy,
3982 const DeclSpec &DS,
3983 SourceLocation IdLoc,
3984 SourceLocation LParenLoc,
3985 ArrayRef<Expr *> Args,
3986 SourceLocation RParenLoc,
3987 SourceLocation EllipsisLoc) {
3988 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3989 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3990 DS, IdLoc, List, EllipsisLoc);
3991}
3992
3993namespace {
3994
3995// Callback to only accept typo corrections that can be a valid C++ member
3996// intializer: either a non-static field member or a base class.
3997class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3998public:
3999 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4000 : ClassDecl(ClassDecl) {}
4001
4002 bool ValidateCandidate(const TypoCorrection &candidate) override {
4003 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4004 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4005 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4006 return isa<TypeDecl>(ND);
4007 }
4008 return false;
4009 }
4010
4011 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4012 return std::make_unique<MemInitializerValidatorCCC>(*this);
4013 }
4014
4015private:
4016 CXXRecordDecl *ClassDecl;
4017};
4018
4019}
4020
4021ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4022 CXXScopeSpec &SS,
4023 ParsedType TemplateTypeTy,
4024 IdentifierInfo *MemberOrBase) {
4025 if (SS.getScopeRep() || TemplateTypeTy)
4026 return nullptr;
4027 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4028 if (Result.empty())
4029 return nullptr;
4030 ValueDecl *Member;
4031 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4032 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4033 return Member;
4034 return nullptr;
4035}
4036
4037/// Handle a C++ member initializer.
4038MemInitResult
4039Sema::BuildMemInitializer(Decl *ConstructorD,
4040 Scope *S,
4041 CXXScopeSpec &SS,
4042 IdentifierInfo *MemberOrBase,
4043 ParsedType TemplateTypeTy,
4044 const DeclSpec &DS,
4045 SourceLocation IdLoc,
4046 Expr *Init,
4047 SourceLocation EllipsisLoc) {
4048 ExprResult Res = CorrectDelayedTyposInExpr(Init);
4049 if (!Res.isUsable())
4050 return true;
4051 Init = Res.get();
4052
4053 if (!ConstructorD)
4054 return true;
4055
4056 AdjustDeclIfTemplate(ConstructorD);
4057
4058 CXXConstructorDecl *Constructor
4059 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4060 if (!Constructor) {
4061 // The user wrote a constructor initializer on a function that is
4062 // not a C++ constructor. Ignore the error for now, because we may
4063 // have more member initializers coming; we'll diagnose it just
4064 // once in ActOnMemInitializers.
4065 return true;
4066 }
4067
4068 CXXRecordDecl *ClassDecl = Constructor->getParent();
4069
4070 // C++ [class.base.init]p2:
4071 // Names in a mem-initializer-id are looked up in the scope of the
4072 // constructor's class and, if not found in that scope, are looked
4073 // up in the scope containing the constructor's definition.
4074 // [Note: if the constructor's class contains a member with the
4075 // same name as a direct or virtual base class of the class, a
4076 // mem-initializer-id naming the member or base class and composed
4077 // of a single identifier refers to the class member. A
4078 // mem-initializer-id for the hidden base class may be specified
4079 // using a qualified name. ]
4080
4081 // Look for a member, first.
4082 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4083 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4084 if (EllipsisLoc.isValid())
4085 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4086 << MemberOrBase
4087 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4088
4089 return BuildMemberInitializer(Member, Init, IdLoc);
4090 }
4091 // It didn't name a member, so see if it names a class.
4092 QualType BaseType;
4093 TypeSourceInfo *TInfo = nullptr;
4094
4095 if (TemplateTypeTy) {
4096 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4097 if (BaseType.isNull())
4098 return true;
4099 } else if (DS.getTypeSpecType() == TST_decltype) {
4100 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4101 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4102 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4103 return true;
4104 } else {
4105 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4106 LookupParsedName(R, S, &SS);
4107
4108 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4109 if (!TyD) {
4110 if (R.isAmbiguous()) return true;
4111
4112 // We don't want access-control diagnostics here.
4113 R.suppressDiagnostics();
4114
4115 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4116 bool NotUnknownSpecialization = false;
4117 DeclContext *DC = computeDeclContext(SS, false);
4118 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4119 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4120
4121 if (!NotUnknownSpecialization) {
4122 // When the scope specifier can refer to a member of an unknown
4123 // specialization, we take it as a type name.
4124 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4125 SS.getWithLocInContext(Context),
4126 *MemberOrBase, IdLoc);
4127 if (BaseType.isNull())
4128 return true;
4129
4130 TInfo = Context.CreateTypeSourceInfo(BaseType);
4131 DependentNameTypeLoc TL =
4132 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4133 if (!TL.isNull()) {
4134 TL.setNameLoc(IdLoc);
4135 TL.setElaboratedKeywordLoc(SourceLocation());
4136 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4137 }
4138
4139 R.clear();
4140 R.setLookupName(MemberOrBase);
4141 }
4142 }
4143
4144 // If no results were found, try to correct typos.
4145 TypoCorrection Corr;
4146 MemInitializerValidatorCCC CCC(ClassDecl);
4147 if (R.empty() && BaseType.isNull() &&
4148 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4149 CCC, CTK_ErrorRecovery, ClassDecl))) {
4150 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4151 // We have found a non-static data member with a similar
4152 // name to what was typed; complain and initialize that
4153 // member.
4154 diagnoseTypo(Corr,
4155 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4156 << MemberOrBase << true);
4157 return BuildMemberInitializer(Member, Init, IdLoc);
4158 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4159 const CXXBaseSpecifier *DirectBaseSpec;
4160 const CXXBaseSpecifier *VirtualBaseSpec;
4161 if (FindBaseInitializer(*this, ClassDecl,
4162 Context.getTypeDeclType(Type),
4163 DirectBaseSpec, VirtualBaseSpec)) {
4164 // We have found a direct or virtual base class with a
4165 // similar name to what was typed; complain and initialize
4166 // that base class.
4167 diagnoseTypo(Corr,
4168 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4169 << MemberOrBase << false,
4170 PDiag() /*Suppress note, we provide our own.*/);
4171
4172 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4173 : VirtualBaseSpec;
4174 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4175 << BaseSpec->getType() << BaseSpec->getSourceRange();
4176
4177 TyD = Type;
4178 }
4179 }
4180 }
4181
4182 if (!TyD && BaseType.isNull()) {
4183 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4184 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4185 return true;
4186 }
4187 }
4188
4189 if (BaseType.isNull()) {
4190 BaseType = Context.getTypeDeclType(TyD);
4191 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4192 if (SS.isSet()) {
4193 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4194 BaseType);
4195 TInfo = Context.CreateTypeSourceInfo(BaseType);
4196 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4197 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4198 TL.setElaboratedKeywordLoc(SourceLocation());
4199 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4200 }
4201 }
4202 }
4203
4204 if (!TInfo)
4205 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4206
4207 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4208}
4209
4210MemInitResult
4211Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4212 SourceLocation IdLoc) {
4213 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4214 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4215 assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4216, __PRETTY_FUNCTION__))
4216 "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4216, __PRETTY_FUNCTION__))
;
4217
4218 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4219 return true;
4220
4221 if (Member->isInvalidDecl())
4222 return true;
4223
4224 MultiExprArg Args;
4225 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4226 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4227 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4228 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4229 } else {
4230 // Template instantiation doesn't reconstruct ParenListExprs for us.
4231 Args = Init;
4232 }
4233
4234 SourceRange InitRange = Init->getSourceRange();
4235
4236 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4237 // Can't check initialization for a member of dependent type or when
4238 // any of the arguments are type-dependent expressions.
4239 DiscardCleanupsInEvaluationContext();
4240 } else {
4241 bool InitList = false;
4242 if (isa<InitListExpr>(Init)) {
4243 InitList = true;
4244 Args = Init;
4245 }
4246
4247 // Initialize the member.
4248 InitializedEntity MemberEntity =
4249 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4250 : InitializedEntity::InitializeMember(IndirectMember,
4251 nullptr);
4252 InitializationKind Kind =
4253 InitList ? InitializationKind::CreateDirectList(
4254 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4255 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4256 InitRange.getEnd());
4257
4258 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4259 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4260 nullptr);
4261 if (MemberInit.isInvalid())
4262 return true;
4263
4264 // C++11 [class.base.init]p7:
4265 // The initialization of each base and member constitutes a
4266 // full-expression.
4267 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4268 /*DiscardedValue*/ false);
4269 if (MemberInit.isInvalid())
4270 return true;
4271
4272 Init = MemberInit.get();
4273 }
4274
4275 if (DirectMember) {
4276 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4277 InitRange.getBegin(), Init,
4278 InitRange.getEnd());
4279 } else {
4280 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4281 InitRange.getBegin(), Init,
4282 InitRange.getEnd());
4283 }
4284}
4285
4286MemInitResult
4287Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4288 CXXRecordDecl *ClassDecl) {
4289 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4290 if (!LangOpts.CPlusPlus11)
4291 return Diag(NameLoc, diag::err_delegating_ctor)
4292 << TInfo->getTypeLoc().getLocalSourceRange();
4293 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4294
4295 bool InitList = true;
4296 MultiExprArg Args = Init;
4297 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4298 InitList = false;
4299 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4300 }
4301
4302 SourceRange InitRange = Init->getSourceRange();
4303 // Initialize the object.
4304 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4305 QualType(ClassDecl->getTypeForDecl(), 0));
4306 InitializationKind Kind =
4307 InitList ? InitializationKind::CreateDirectList(
4308 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4309 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4310 InitRange.getEnd());
4311 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4312 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4313 Args, nullptr);
4314 if (DelegationInit.isInvalid())
4315 return true;
4316
4317 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4318, __PRETTY_FUNCTION__))
4318 "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4318, __PRETTY_FUNCTION__))
;
4319
4320 // C++11 [class.base.init]p7:
4321 // The initialization of each base and member constitutes a
4322 // full-expression.
4323 DelegationInit = ActOnFinishFullExpr(
4324 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4325 if (DelegationInit.isInvalid())
4326 return true;
4327
4328 // If we are in a dependent context, template instantiation will
4329 // perform this type-checking again. Just save the arguments that we
4330 // received in a ParenListExpr.
4331 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4332 // of the information that we have about the base
4333 // initializer. However, deconstructing the ASTs is a dicey process,
4334 // and this approach is far more likely to get the corner cases right.
4335 if (CurContext->isDependentContext())
4336 DelegationInit = Init;
4337
4338 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4339 DelegationInit.getAs<Expr>(),
4340 InitRange.getEnd());
4341}
4342
4343MemInitResult
4344Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4345 Expr *Init, CXXRecordDecl *ClassDecl,
4346 SourceLocation EllipsisLoc) {
4347 SourceLocation BaseLoc
4348 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4349
4350 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4351 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4352 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4353
4354 // C++ [class.base.init]p2:
4355 // [...] Unless the mem-initializer-id names a nonstatic data
4356 // member of the constructor's class or a direct or virtual base
4357 // of that class, the mem-initializer is ill-formed. A
4358 // mem-initializer-list can initialize a base class using any
4359 // name that denotes that base class type.
4360 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4361
4362 SourceRange InitRange = Init->getSourceRange();
4363 if (EllipsisLoc.isValid()) {
4364 // This is a pack expansion.
4365 if (!BaseType->containsUnexpandedParameterPack()) {
4366 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4367 << SourceRange(BaseLoc, InitRange.getEnd());
4368
4369 EllipsisLoc = SourceLocation();
4370 }
4371 } else {
4372 // Check for any unexpanded parameter packs.
4373 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4374 return true;
4375
4376 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4377 return true;
4378 }
4379
4380 // Check for direct and virtual base classes.
4381 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4382 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4383 if (!Dependent) {
4384 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4385 BaseType))
4386 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4387
4388 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4389 VirtualBaseSpec);
4390
4391 // C++ [base.class.init]p2:
4392 // Unless the mem-initializer-id names a nonstatic data member of the
4393 // constructor's class or a direct or virtual base of that class, the
4394 // mem-initializer is ill-formed.
4395 if (!DirectBaseSpec && !VirtualBaseSpec) {
4396 // If the class has any dependent bases, then it's possible that
4397 // one of those types will resolve to the same type as
4398 // BaseType. Therefore, just treat this as a dependent base
4399 // class initialization. FIXME: Should we try to check the
4400 // initialization anyway? It seems odd.
4401 if (ClassDecl->hasAnyDependentBases())
4402 Dependent = true;
4403 else
4404 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4405 << BaseType << Context.getTypeDeclType(ClassDecl)
4406 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4407 }
4408 }
4409
4410 if (Dependent) {
4411 DiscardCleanupsInEvaluationContext();
4412
4413 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4414 /*IsVirtual=*/false,
4415 InitRange.getBegin(), Init,
4416 InitRange.getEnd(), EllipsisLoc);
4417 }
4418
4419 // C++ [base.class.init]p2:
4420 // If a mem-initializer-id is ambiguous because it designates both
4421 // a direct non-virtual base class and an inherited virtual base
4422 // class, the mem-initializer is ill-formed.
4423 if (DirectBaseSpec && VirtualBaseSpec)
4424 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4425 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4426
4427 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4428 if (!BaseSpec)
4429 BaseSpec = VirtualBaseSpec;
4430
4431 // Initialize the base.
4432 bool InitList = true;
4433 MultiExprArg Args = Init;
4434 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4435 InitList = false;
4436 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4437 }
4438
4439 InitializedEntity BaseEntity =
4440 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4441 InitializationKind Kind =
4442 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4443 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4444 InitRange.getEnd());
4445 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4446 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4447 if (BaseInit.isInvalid())
4448 return true;
4449
4450 // C++11 [class.base.init]p7:
4451 // The initialization of each base and member constitutes a
4452 // full-expression.
4453 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4454 /*DiscardedValue*/ false);
4455 if (BaseInit.isInvalid())
4456 return true;
4457
4458 // If we are in a dependent context, template instantiation will
4459 // perform this type-checking again. Just save the arguments that we
4460 // received in a ParenListExpr.
4461 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4462 // of the information that we have about the base
4463 // initializer. However, deconstructing the ASTs is a dicey process,
4464 // and this approach is far more likely to get the corner cases right.
4465 if (CurContext->isDependentContext())
4466 BaseInit = Init;
4467
4468 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4469 BaseSpec->isVirtual(),
4470 InitRange.getBegin(),
4471 BaseInit.getAs<Expr>(),
4472 InitRange.getEnd(), EllipsisLoc);
4473}
4474
4475// Create a static_cast\<T&&>(expr).
4476static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4477 if (T.isNull()) T = E->getType();
4478 QualType TargetType = SemaRef.BuildReferenceType(
4479 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4480 SourceLocation ExprLoc = E->getBeginLoc();
4481 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4482 TargetType, ExprLoc);
4483
4484 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4485 SourceRange(ExprLoc, ExprLoc),
4486 E->getSourceRange()).get();
4487}
4488
4489/// ImplicitInitializerKind - How an implicit base or member initializer should
4490/// initialize its base or member.
4491enum ImplicitInitializerKind {
4492 IIK_Default,
4493 IIK_Copy,
4494 IIK_Move,
4495 IIK_Inherit
4496};
4497
4498static bool
4499BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4500 ImplicitInitializerKind ImplicitInitKind,
4501 CXXBaseSpecifier *BaseSpec,
4502 bool IsInheritedVirtualBase,
4503 CXXCtorInitializer *&CXXBaseInit) {
4504 InitializedEntity InitEntity
4505 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4506 IsInheritedVirtualBase);
4507
4508 ExprResult BaseInit;
4509
4510 switch (ImplicitInitKind) {
4511 case IIK_Inherit:
4512 case IIK_Default: {
4513 InitializationKind InitKind
4514 = InitializationKind::CreateDefault(Constructor->getLocation());
4515 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4516 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4517 break;
4518 }
4519
4520 case IIK_Move:
4521 case IIK_Copy: {
4522 bool Moving = ImplicitInitKind == IIK_Move;
4523 ParmVarDecl *Param = Constructor->getParamDecl(0);
4524 QualType ParamType = Param->getType().getNonReferenceType();
4525
4526 Expr *CopyCtorArg =
4527 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4528 SourceLocation(), Param, false,
4529 Constructor->getLocation(), ParamType,
4530 VK_LValue, nullptr);
4531
4532 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4533
4534 // Cast to the base class to avoid ambiguities.
4535 QualType ArgTy =
4536 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4537 ParamType.getQualifiers());
4538
4539 if (Moving) {
4540 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4541 }
4542
4543 CXXCastPath BasePath;
4544 BasePath.push_back(BaseSpec);
4545 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4546 CK_UncheckedDerivedToBase,
4547 Moving ? VK_XValue : VK_LValue,
4548 &BasePath).get();
4549
4550 InitializationKind InitKind
4551 = InitializationKind::CreateDirect(Constructor->getLocation(),
4552 SourceLocation(), SourceLocation());
4553 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4554 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4555 break;
4556 }
4557 }
4558
4559 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4560 if (BaseInit.isInvalid())
4561 return true;
4562
4563 CXXBaseInit =
4564 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4565 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4566 SourceLocation()),
4567 BaseSpec->isVirtual(),
4568 SourceLocation(),
4569 BaseInit.getAs<Expr>(),
4570 SourceLocation(),
4571 SourceLocation());
4572
4573 return false;
4574}
4575
4576static bool RefersToRValueRef(Expr *MemRef) {
4577 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4578 return Referenced->getType()->isRValueReferenceType();
4579}
4580
4581static bool
4582BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4583 ImplicitInitializerKind ImplicitInitKind,
4584 FieldDecl *Field, IndirectFieldDecl *Indirect,
4585 CXXCtorInitializer *&CXXMemberInit) {
4586 if (Field->isInvalidDecl())
4587 return true;
4588
4589 SourceLocation Loc = Constructor->getLocation();
4590
4591 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4592 bool Moving = ImplicitInitKind == IIK_Move;
4593 ParmVarDecl *Param = Constructor->getParamDecl(0);
4594 QualType ParamType = Param->getType().getNonReferenceType();
4595
4596 // Suppress copying zero-width bitfields.
4597 if (Field->isZeroLengthBitField(SemaRef.Context))
4598 return false;
4599
4600 Expr *MemberExprBase =
4601 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4602 SourceLocation(), Param, false,
4603 Loc, ParamType, VK_LValue, nullptr);
4604
4605 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4606
4607 if (Moving) {
4608 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4609 }
4610
4611 // Build a reference to this field within the parameter.
4612 CXXScopeSpec SS;
4613 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4614 Sema::LookupMemberName);
4615 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4616 : cast<ValueDecl>(Field), AS_public);
4617 MemberLookup.resolveKind();
4618 ExprResult CtorArg
4619 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4620 ParamType, Loc,
4621 /*IsArrow=*/false,
4622 SS,
4623 /*TemplateKWLoc=*/SourceLocation(),
4624 /*FirstQualifierInScope=*/nullptr,
4625 MemberLookup,
4626 /*TemplateArgs=*/nullptr,
4627 /*S*/nullptr);
4628 if (CtorArg.isInvalid())
4629 return true;
4630
4631 // C++11 [class.copy]p15:
4632 // - if a member m has rvalue reference type T&&, it is direct-initialized
4633 // with static_cast<T&&>(x.m);
4634 if (RefersToRValueRef(CtorArg.get())) {
4635 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4636 }
4637
4638 InitializedEntity Entity =
4639 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4640 /*Implicit*/ true)
4641 : InitializedEntity::InitializeMember(Field, nullptr,
4642 /*Implicit*/ true);
4643
4644 // Direct-initialize to use the copy constructor.
4645 InitializationKind InitKind =
4646 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4647
4648 Expr *CtorArgE = CtorArg.getAs<Expr>();
4649 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4650 ExprResult MemberInit =
4651 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4652 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4653 if (MemberInit.isInvalid())
4654 return true;
4655
4656 if (Indirect)
4657 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4658 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4659 else
4660 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4661 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4662 return false;
4663 }
4664
4665 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4666, __PRETTY_FUNCTION__))
4666 "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4666, __PRETTY_FUNCTION__))
;
4667
4668 QualType FieldBaseElementType =
4669 SemaRef.Context.getBaseElementType(Field->getType());
4670
4671 if (FieldBaseElementType->isRecordType()) {
4672 InitializedEntity InitEntity =
4673 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4674 /*Implicit*/ true)
4675 : InitializedEntity::InitializeMember(Field, nullptr,
4676 /*Implicit*/ true);
4677 InitializationKind InitKind =
4678 InitializationKind::CreateDefault(Loc);
4679
4680 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4681 ExprResult MemberInit =
4682 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4683
4684 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4685 if (MemberInit.isInvalid())
4686 return true;
4687
4688 if (Indirect)
4689 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4690 Indirect, Loc,
4691 Loc,
4692 MemberInit.get(),
4693 Loc);
4694 else
4695 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4696 Field, Loc, Loc,
4697 MemberInit.get(),
4698 Loc);
4699 return false;
4700 }
4701
4702 if (!Field->getParent()->isUnion()) {
4703 if (FieldBaseElementType->isReferenceType()) {
4704 SemaRef.Diag(Constructor->getLocation(),
4705 diag::err_uninitialized_member_in_ctor)
4706 << (int)Constructor->isImplicit()
4707 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4708 << 0 << Field->getDeclName();
4709 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4710 return true;
4711 }
4712
4713 if (FieldBaseElementType.isConstQualified()) {
4714 SemaRef.Diag(Constructor->getLocation(),
4715 diag::err_uninitialized_member_in_ctor)
4716 << (int)Constructor->isImplicit()
4717 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4718 << 1 << Field->getDeclName();
4719 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4720 return true;
4721 }
4722 }
4723
4724 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4725 // ARC and Weak:
4726 // Default-initialize Objective-C pointers to NULL.
4727 CXXMemberInit
4728 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4729 Loc, Loc,
4730 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4731 Loc);
4732 return false;
4733 }
4734
4735 // Nothing to initialize.
4736 CXXMemberInit = nullptr;
4737 return false;
4738}
4739
4740namespace {
4741struct BaseAndFieldInfo {
4742 Sema &S;
4743 CXXConstructorDecl *Ctor;
4744 bool AnyErrorsInInits;
4745 ImplicitInitializerKind IIK;
4746 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4747 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4748 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4749
4750 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4751 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4752 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4753 if (Ctor->getInheritedConstructor())
4754 IIK = IIK_Inherit;
4755 else if (Generated && Ctor->isCopyConstructor())
4756 IIK = IIK_Copy;
4757 else if (Generated && Ctor->isMoveConstructor())
4758 IIK = IIK_Move;
4759 else
4760 IIK = IIK_Default;
4761 }
4762
4763 bool isImplicitCopyOrMove() const {
4764 switch (IIK) {
4765 case IIK_Copy:
4766 case IIK_Move:
4767 return true;
4768
4769 case IIK_Default:
4770 case IIK_Inherit:
4771 return false;
4772 }
4773
4774 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4774)
;
4775 }
4776
4777 bool addFieldInitializer(CXXCtorInitializer *Init) {
4778 AllToInit.push_back(Init);
4779
4780 // Check whether this initializer makes the field "used".
4781 if (Init->getInit()->HasSideEffects(S.Context))
4782 S.UnusedPrivateFields.remove(Init->getAnyMember());
4783
4784 return false;
4785 }
4786
4787 bool isInactiveUnionMember(FieldDecl *Field) {
4788 RecordDecl *Record = Field->getParent();
4789 if (!Record->isUnion())
4790 return false;
4791
4792 if (FieldDecl *Active =
4793 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4794 return Active != Field->getCanonicalDecl();
4795
4796 // In an implicit copy or move constructor, ignore any in-class initializer.
4797 if (isImplicitCopyOrMove())
4798 return true;
4799
4800 // If there's no explicit initialization, the field is active only if it
4801 // has an in-class initializer...
4802 if (Field->hasInClassInitializer())
4803 return false;
4804 // ... or it's an anonymous struct or union whose class has an in-class
4805 // initializer.
4806 if (!Field->isAnonymousStructOrUnion())
4807 return true;
4808 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4809 return !FieldRD->hasInClassInitializer();
4810 }
4811
4812 /// Determine whether the given field is, or is within, a union member
4813 /// that is inactive (because there was an initializer given for a different
4814 /// member of the union, or because the union was not initialized at all).
4815 bool isWithinInactiveUnionMember(FieldDecl *Field,
4816 IndirectFieldDecl *Indirect) {
4817 if (!Indirect)
4818 return isInactiveUnionMember(Field);
4819
4820 for (auto *C : Indirect->chain()) {
4821 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4822 if (Field && isInactiveUnionMember(Field))
4823 return true;
4824 }
4825 return false;
4826 }
4827};
4828}
4829
4830/// Determine whether the given type is an incomplete or zero-lenfgth
4831/// array type.
4832static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4833 if (T->isIncompleteArrayType())
4834 return true;
4835
4836 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4837 if (!ArrayT->getSize())
4838 return true;
4839
4840 T = ArrayT->getElementType();
4841 }
4842
4843 return false;
4844}
4845
4846static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4847 FieldDecl *Field,
4848 IndirectFieldDecl *Indirect = nullptr) {
4849 if (Field->isInvalidDecl())
4850 return false;
4851
4852 // Overwhelmingly common case: we have a direct initializer for this field.
4853 if (CXXCtorInitializer *Init =
4854 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4855 return Info.addFieldInitializer(Init);
4856
4857 // C++11 [class.base.init]p8:
4858 // if the entity is a non-static data member that has a
4859 // brace-or-equal-initializer and either
4860 // -- the constructor's class is a union and no other variant member of that
4861 // union is designated by a mem-initializer-id or
4862 // -- the constructor's class is not a union, and, if the entity is a member
4863 // of an anonymous union, no other member of that union is designated by
4864 // a mem-initializer-id,
4865 // the entity is initialized as specified in [dcl.init].
4866 //
4867 // We also apply the same rules to handle anonymous structs within anonymous
4868 // unions.
4869 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4870 return false;
4871
4872 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4873 ExprResult DIE =
4874 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4875 if (DIE.isInvalid())
4876 return true;
4877
4878 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4879 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4880
4881 CXXCtorInitializer *Init;
4882 if (Indirect)
4883 Init = new (SemaRef.Context)
4884 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4885 SourceLocation(), DIE.get(), SourceLocation());
4886 else
4887 Init = new (SemaRef.Context)
4888 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4889 SourceLocation(), DIE.get(), SourceLocation());
4890 return Info.addFieldInitializer(Init);
4891 }
4892
4893 // Don't initialize incomplete or zero-length arrays.
4894 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4895 return false;
4896
4897 // Don't try to build an implicit initializer if there were semantic
4898 // errors in any of the initializers (and therefore we might be
4899 // missing some that the user actually wrote).
4900 if (Info.AnyErrorsInInits)
4901 return false;
4902
4903 CXXCtorInitializer *Init = nullptr;
4904 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4905 Indirect, Init))
4906 return true;
4907
4908 if (!Init)
4909 return false;
4910
4911 return Info.addFieldInitializer(Init);
4912}
4913
4914bool
4915Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4916 CXXCtorInitializer *Initializer) {
4917 assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast<
void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 4917, __PRETTY_FUNCTION__))
;
4918 Constructor->setNumCtorInitializers(1);
4919 CXXCtorInitializer **initializer =
4920 new (Context) CXXCtorInitializer*[1];
4921 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4922 Constructor->setCtorInitializers(initializer);
4923
4924 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4925 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4926 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4927 }
4928
4929 DelegatingCtorDecls.push_back(Constructor);
4930
4931 DiagnoseUninitializedFields(*this, Constructor);
4932
4933 return false;
4934}
4935
4936bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4937 ArrayRef<CXXCtorInitializer *> Initializers) {
4938 if (Constructor->isDependentContext()) {
4939 // Just store the initializers as written, they will be checked during
4940 // instantiation.
4941 if (!Initializers.empty()) {
4942 Constructor->setNumCtorInitializers(Initializers.size());
4943 CXXCtorInitializer **baseOrMemberInitializers =
4944 new (Context) CXXCtorInitializer*[Initializers.size()];
4945 memcpy(baseOrMemberInitializers, Initializers.data(),
4946 Initializers.size() * sizeof(CXXCtorInitializer*));
4947 Constructor->setCtorInitializers(baseOrMemberInitializers);
4948 }
4949
4950 // Let template instantiation know whether we had errors.
4951 if (AnyErrors)
4952 Constructor->setInvalidDecl();
4953
4954 return false;
4955 }
4956
4957 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4958
4959 // We need to build the initializer AST according to order of construction
4960 // and not what user specified in the Initializers list.
4961 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4962 if (!ClassDecl)
4963 return true;
4964
4965 bool HadError = false;
4966
4967 for (unsigned i = 0; i < Initializers.size(); i++) {
4968 CXXCtorInitializer *Member = Initializers[i];
4969
4970 if (Member->isBaseInitializer())
4971 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4972 else {
4973 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4974
4975 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4976 for (auto *C : F->chain()) {
4977 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4978 if (FD && FD->getParent()->isUnion())
4979 Info.ActiveUnionMember.insert(std::make_pair(
4980 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4981 }
4982 } else if (FieldDecl *FD = Member->getMember()) {
4983 if (FD->getParent()->isUnion())
4984 Info.ActiveUnionMember.insert(std::make_pair(
4985 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4986 }
4987 }
4988 }
4989
4990 // Keep track of the direct virtual bases.
4991 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4992 for (auto &I : ClassDecl->bases()) {
4993 if (I.isVirtual())
4994 DirectVBases.insert(&I);
4995 }
4996
4997 // Push virtual bases before others.
4998 for (auto &VBase : ClassDecl->vbases()) {
4999 if (CXXCtorInitializer *Value
5000 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5001 // [class.base.init]p7, per DR257:
5002 // A mem-initializer where the mem-initializer-id names a virtual base
5003 // class is ignored during execution of a constructor of any class that
5004 // is not the most derived class.
5005 if (ClassDecl->isAbstract()) {
5006 // FIXME: Provide a fixit to remove the base specifier. This requires
5007 // tracking the location of the associated comma for a base specifier.
5008 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5009 << VBase.getType() << ClassDecl;
5010 DiagnoseAbstractType(ClassDecl);
5011 }
5012
5013 Info.AllToInit.push_back(Value);
5014 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5015 // [class.base.init]p8, per DR257:
5016 // If a given [...] base class is not named by a mem-initializer-id
5017 // [...] and the entity is not a virtual base class of an abstract
5018 // class, then [...] the entity is default-initialized.
5019 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5020 CXXCtorInitializer *CXXBaseInit;
5021 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5022 &VBase, IsInheritedVirtualBase,
5023 CXXBaseInit)) {
5024 HadError = true;
5025 continue;
5026 }
5027
5028 Info.AllToInit.push_back(CXXBaseInit);
5029 }
5030 }
5031
5032 // Non-virtual bases.
5033 for (auto &Base : ClassDecl->bases()) {
5034 // Virtuals are in the virtual base list and already constructed.
5035 if (Base.isVirtual())
5036 continue;
5037
5038 if (CXXCtorInitializer *Value
5039 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5040 Info.AllToInit.push_back(Value);
5041 } else if (!AnyErrors) {
5042 CXXCtorInitializer *CXXBaseInit;
5043 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5044 &Base, /*IsInheritedVirtualBase=*/false,
5045 CXXBaseInit)) {
5046 HadError = true;
5047 continue;
5048 }
5049
5050 Info.AllToInit.push_back(CXXBaseInit);
5051 }
5052 }
5053
5054 // Fields.
5055 for (auto *Mem : ClassDecl->decls()) {
5056 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5057 // C++ [class.bit]p2:
5058 // A declaration for a bit-field that omits the identifier declares an
5059 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5060 // initialized.
5061 if (F->isUnnamedBitfield())
5062 continue;
5063
5064 // If we're not generating the implicit copy/move constructor, then we'll
5065 // handle anonymous struct/union fields based on their individual
5066 // indirect fields.
5067 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5068 continue;
5069
5070 if (CollectFieldInitializer(*this, Info, F))
5071 HadError = true;
5072 continue;
5073 }
5074
5075 // Beyond this point, we only consider default initialization.
5076 if (Info.isImplicitCopyOrMove())
5077 continue;
5078
5079 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5080 if (F->getType()->isIncompleteArrayType()) {
5081 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5082, __PRETTY_FUNCTION__))
5082 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5082, __PRETTY_FUNCTION__))
;
5083 continue;
5084 }
5085
5086 // Initialize each field of an anonymous struct individually.
5087 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5088 HadError = true;
5089
5090 continue;
5091 }
5092 }
5093
5094 unsigned NumInitializers = Info.AllToInit.size();
5095 if (NumInitializers > 0) {
5096 Constructor->setNumCtorInitializers(NumInitializers);
5097 CXXCtorInitializer **baseOrMemberInitializers =
5098 new (Context) CXXCtorInitializer*[NumInitializers];
5099 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5100 NumInitializers * sizeof(CXXCtorInitializer*));
5101 Constructor->setCtorInitializers(baseOrMemberInitializers);
5102
5103 // Constructors implicitly reference the base and member
5104 // destructors.
5105 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5106 Constructor->getParent());
5107 }
5108
5109 return HadError;
5110}
5111
5112static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5113 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5114 const RecordDecl *RD = RT->getDecl();
5115 if (RD->isAnonymousStructOrUnion()) {
5116 for (auto *Field : RD->fields())
5117 PopulateKeysForFields(Field, IdealInits);
5118 return;
5119 }
5120 }
5121 IdealInits.push_back(Field->getCanonicalDecl());
5122}
5123
5124static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5125 return Context.getCanonicalType(BaseType).getTypePtr();
5126}
5127
5128static const void *GetKeyForMember(ASTContext &Context,
5129 CXXCtorInitializer *Member) {
5130 if (!Member->isAnyMemberInitializer())
5131 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5132
5133 return Member->getAnyMember()->getCanonicalDecl();
5134}
5135
5136static void DiagnoseBaseOrMemInitializerOrder(
5137 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5138 ArrayRef<CXXCtorInitializer *> Inits) {
5139 if (Constructor->getDeclContext()->isDependentContext())
5140 return;
5141
5142 // Don't check initializers order unless the warning is enabled at the
5143 // location of at least one initializer.
5144 bool ShouldCheckOrder = false;
5145 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5146 CXXCtorInitializer *Init = Inits[InitIndex];
5147 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5148 Init->getSourceLocation())) {
5149 ShouldCheckOrder = true;
5150 break;
5151 }
5152 }
5153 if (!ShouldCheckOrder)
5154 return;
5155
5156 // Build the list of bases and members in the order that they'll
5157 // actually be initialized. The explicit initializers should be in
5158 // this same order but may be missing things.
5159 SmallVector<const void*, 32> IdealInitKeys;
5160
5161 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5162
5163 // 1. Virtual bases.
5164 for (const auto &VBase : ClassDecl->vbases())
5165 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5166
5167 // 2. Non-virtual bases.
5168 for (const auto &Base : ClassDecl->bases()) {
5169 if (Base.isVirtual())
5170 continue;
5171 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5172 }
5173
5174 // 3. Direct fields.
5175 for (auto *Field : ClassDecl->fields()) {
5176 if (Field->isUnnamedBitfield())
5177 continue;
5178
5179 PopulateKeysForFields(Field, IdealInitKeys);
5180 }
5181
5182 unsigned NumIdealInits = IdealInitKeys.size();
5183 unsigned IdealIndex = 0;
5184
5185 CXXCtorInitializer *PrevInit = nullptr;
5186 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5187 CXXCtorInitializer *Init = Inits[InitIndex];
5188 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5189
5190 // Scan forward to try to find this initializer in the idealized
5191 // initializers list.
5192 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5193 if (InitKey == IdealInitKeys[IdealIndex])
5194 break;
5195
5196 // If we didn't find this initializer, it must be because we
5197 // scanned past it on a previous iteration. That can only
5198 // happen if we're out of order; emit a warning.
5199 if (IdealIndex == NumIdealInits && PrevInit) {
5200 Sema::SemaDiagnosticBuilder D =
5201 SemaRef.Diag(PrevInit->getSourceLocation(),
5202 diag::warn_initializer_out_of_order);
5203
5204 if (PrevInit->isAnyMemberInitializer())
5205 D << 0 << PrevInit->getAnyMember()->getDeclName();
5206 else
5207 D << 1 << PrevInit->getTypeSourceInfo()->getType();
5208
5209 if (Init->isAnyMemberInitializer())
5210 D << 0 << Init->getAnyMember()->getDeclName();
5211 else
5212 D << 1 << Init->getTypeSourceInfo()->getType();
5213
5214 // Move back to the initializer's location in the ideal list.
5215 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5216 if (InitKey == IdealInitKeys[IdealIndex])
5217 break;
5218
5219 assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5220, __PRETTY_FUNCTION__))
5220 "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5220, __PRETTY_FUNCTION__))
;
5221 }
5222
5223 PrevInit = Init;
5224 }
5225}
5226
5227namespace {
5228bool CheckRedundantInit(Sema &S,
5229 CXXCtorInitializer *Init,
5230 CXXCtorInitializer *&PrevInit) {
5231 if (!PrevInit) {
5232 PrevInit = Init;
5233 return false;
5234 }
5235
5236 if (FieldDecl *Field = Init->getAnyMember())
5237 S.Diag(Init->getSourceLocation(),
5238 diag::err_multiple_mem_initialization)
5239 << Field->getDeclName()
5240 << Init->getSourceRange();
5241 else {
5242 const Type *BaseClass = Init->getBaseClass();
5243 assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast
<void> (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5243, __PRETTY_FUNCTION__))
;
5244 S.Diag(Init->getSourceLocation(),
5245 diag::err_multiple_base_initialization)
5246 << QualType(BaseClass, 0)
5247 << Init->getSourceRange();
5248 }
5249 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5250 << 0 << PrevInit->getSourceRange();
5251
5252 return true;
5253}
5254
5255typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5256typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5257
5258bool CheckRedundantUnionInit(Sema &S,
5259 CXXCtorInitializer *Init,
5260 RedundantUnionMap &Unions) {
5261 FieldDecl *Field = Init->getAnyMember();
5262 RecordDecl *Parent = Field->getParent();
5263 NamedDecl *Child = Field;
5264
5265 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5266 if (Parent->isUnion()) {
5267 UnionEntry &En = Unions[Parent];
5268 if (En.first && En.first != Child) {
5269 S.Diag(Init->getSourceLocation(),
5270 diag::err_multiple_mem_union_initialization)
5271 << Field->getDeclName()
5272 << Init->getSourceRange();
5273 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5274 << 0 << En.second->getSourceRange();
5275 return true;
5276 }
5277 if (!En.first) {
5278 En.first = Child;
5279 En.second = Init;
5280 }
5281 if (!Parent->isAnonymousStructOrUnion())
5282 return false;
5283 }
5284
5285 Child = Parent;
5286 Parent = cast<RecordDecl>(Parent->getDeclContext());
5287 }
5288
5289 return false;
5290}
5291}
5292
5293/// ActOnMemInitializers - Handle the member initializers for a constructor.
5294void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5295 SourceLocation ColonLoc,
5296 ArrayRef<CXXCtorInitializer*> MemInits,
5297 bool AnyErrors) {
5298 if (!ConstructorDecl)
5299 return;
5300
5301 AdjustDeclIfTemplate(ConstructorDecl);
5302
5303 CXXConstructorDecl *Constructor
5304 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5305
5306 if (!Constructor) {
5307 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5308 return;
5309 }
5310
5311 // Mapping for the duplicate initializers check.
5312 // For member initializers, this is keyed with a FieldDecl*.
5313 // For base initializers, this is keyed with a Type*.
5314 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5315
5316 // Mapping for the inconsistent anonymous-union initializers check.
5317 RedundantUnionMap MemberUnions;
5318
5319 bool HadError = false;
5320 for (unsigned i = 0; i < MemInits.size(); i++) {
5321 CXXCtorInitializer *Init = MemInits[i];
5322
5323 // Set the source order index.
5324 Init->setSourceOrder(i);
5325
5326 if (Init->isAnyMemberInitializer()) {
5327 const void *Key = GetKeyForMember(Context, Init);
5328 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5329 CheckRedundantUnionInit(*this, Init, MemberUnions))
5330 HadError = true;
5331 } else if (Init->isBaseInitializer()) {
5332 const void *Key = GetKeyForMember(Context, Init);
5333 if (CheckRedundantInit(*this, Init, Members[Key]))
5334 HadError = true;
5335 } else {
5336 assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void>
(0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5336, __PRETTY_FUNCTION__))
;
5337 // This must be the only initializer
5338 if (MemInits.size() != 1) {
5339 Diag(Init->getSourceLocation(),
5340 diag::err_delegating_initializer_alone)
5341 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5342 // We will treat this as being the only initializer.
5343 }
5344 SetDelegatingInitializer(Constructor, MemInits[i]);
5345 // Return immediately as the initializer is set.
5346 return;
5347 }
5348 }
5349
5350 if (HadError)
5351 return;
5352
5353 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5354
5355 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5356
5357 DiagnoseUninitializedFields(*this, Constructor);
5358}
5359
5360void
5361Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5362 CXXRecordDecl *ClassDecl) {
5363 // Ignore dependent contexts. Also ignore unions, since their members never
5364 // have destructors implicitly called.
5365 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5366 return;
5367
5368 // FIXME: all the access-control diagnostics are positioned on the
5369 // field/base declaration. That's probably good; that said, the
5370 // user might reasonably want to know why the destructor is being
5371 // emitted, and we currently don't say.
5372
5373 // Non-static data members.
5374 for (auto *Field : ClassDecl->fields()) {
5375 if (Field->isInvalidDecl())
5376 continue;
5377
5378 // Don't destroy incomplete or zero-length arrays.
5379 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5380 continue;
5381
5382 QualType FieldType = Context.getBaseElementType(Field->getType());
5383
5384 const RecordType* RT = FieldType->getAs<RecordType>();
5385 if (!RT)
5386 continue;
5387
5388 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5389 if (FieldClassDecl->isInvalidDecl())
5390 continue;
5391 if (FieldClassDecl->hasIrrelevantDestructor())
5392 continue;
5393 // The destructor for an implicit anonymous union member is never invoked.
5394 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5395 continue;
5396
5397 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5398 assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5398, __PRETTY_FUNCTION__))
;
5399 CheckDestructorAccess(Field->getLocation(), Dtor,
5400 PDiag(diag::err_access_dtor_field)
5401 << Field->getDeclName()
5402 << FieldType);
5403
5404 MarkFunctionReferenced(Location, Dtor);
5405 DiagnoseUseOfDecl(Dtor, Location);
5406 }
5407
5408 // We only potentially invoke the destructors of potentially constructed
5409 // subobjects.
5410 bool VisitVirtualBases = !ClassDecl->isAbstract();
5411
5412 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5413
5414 // Bases.
5415 for (const auto &Base : ClassDecl->bases()) {
5416 // Bases are always records in a well-formed non-dependent class.
5417 const RecordType *RT = Base.getType()->getAs<RecordType>();
5418
5419 // Remember direct virtual bases.
5420 if (Base.isVirtual()) {
5421 if (!VisitVirtualBases)
5422 continue;
5423 DirectVirtualBases.insert(RT);
5424 }
5425
5426 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5427 // If our base class is invalid, we probably can't get its dtor anyway.
5428 if (BaseClassDecl->isInvalidDecl())
5429 continue;
5430 if (BaseClassDecl->hasIrrelevantDestructor())
5431 continue;
5432
5433 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5434 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5434, __PRETTY_FUNCTION__))
;
5435
5436 // FIXME: caret should be on the start of the class name
5437 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5438 PDiag(diag::err_access_dtor_base)
5439 << Base.getType() << Base.getSourceRange(),
5440 Context.getTypeDeclType(ClassDecl));
5441
5442 MarkFunctionReferenced(Location, Dtor);
5443 DiagnoseUseOfDecl(Dtor, Location);
5444 }
5445
5446 if (!VisitVirtualBases)
5447 return;
5448
5449 // Virtual bases.
5450 for (const auto &VBase : ClassDecl->vbases()) {
5451 // Bases are always records in a well-formed non-dependent class.
5452 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5453
5454 // Ignore direct virtual bases.
5455 if (DirectVirtualBases.count(RT))
5456 continue;
5457
5458 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5459 // If our base class is invalid, we probably can't get its dtor anyway.
5460 if (BaseClassDecl->isInvalidDecl())
5461 continue;
5462 if (BaseClassDecl->hasIrrelevantDestructor())
5463 continue;
5464
5465 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5466 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5466, __PRETTY_FUNCTION__))
;
5467 if (CheckDestructorAccess(
5468 ClassDecl->getLocation(), Dtor,
5469 PDiag(diag::err_access_dtor_vbase)
5470 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5471 Context.getTypeDeclType(ClassDecl)) ==
5472 AR_accessible) {
5473 CheckDerivedToBaseConversion(
5474 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5475 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5476 SourceRange(), DeclarationName(), nullptr);
5477 }
5478
5479 MarkFunctionReferenced(Location, Dtor);
5480 DiagnoseUseOfDecl(Dtor, Location);
5481 }
5482}
5483
5484void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5485 if (!CDtorDecl)
5486 return;
5487
5488 if (CXXConstructorDecl *Constructor
5489 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5490 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5491 DiagnoseUninitializedFields(*this, Constructor);
5492 }
5493}
5494
5495bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5496 if (!getLangOpts().CPlusPlus)
5497 return false;
5498
5499 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5500 if (!RD)
5501 return false;
5502
5503 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5504 // class template specialization here, but doing so breaks a lot of code.
5505
5506 // We can't answer whether something is abstract until it has a
5507 // definition. If it's currently being defined, we'll walk back
5508 // over all the declarations when we have a full definition.
5509 const CXXRecordDecl *Def = RD->getDefinition();
5510 if (!Def || Def->isBeingDefined())
5511 return false;
5512
5513 return RD->isAbstract();
5514}
5515
5516bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5517 TypeDiagnoser &Diagnoser) {
5518 if (!isAbstractType(Loc, T))
5519 return false;
5520
5521 T = Context.getBaseElementType(T);
5522 Diagnoser.diagnose(*this, Loc, T);
5523 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5524 return true;
5525}
5526
5527void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5528 // Check if we've already emitted the list of pure virtual functions
5529 // for this class.
5530 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5531 return;
5532
5533 // If the diagnostic is suppressed, don't emit the notes. We're only
5534 // going to emit them once, so try to attach them to a diagnostic we're
5535 // actually going to show.
5536 if (Diags.isLastDiagnosticIgnored())
5537 return;
5538
5539 CXXFinalOverriderMap FinalOverriders;
5540 RD->getFinalOverriders(FinalOverriders);
5541
5542 // Keep a set of seen pure methods so we won't diagnose the same method
5543 // more than once.
5544 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5545
5546 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5547 MEnd = FinalOverriders.end();
5548 M != MEnd;
5549 ++M) {
5550 for (OverridingMethods::iterator SO = M->second.begin(),
5551 SOEnd = M->second.end();
5552 SO != SOEnd; ++SO) {
5553 // C++ [class.abstract]p4:
5554 // A class is abstract if it contains or inherits at least one
5555 // pure virtual function for which the final overrider is pure
5556 // virtual.
5557
5558 //
5559 if (SO->second.size() != 1)
5560 continue;
5561
5562 if (!SO->second.front().Method->isPure())
5563 continue;
5564
5565 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5566 continue;
5567
5568 Diag(SO->second.front().Method->getLocation(),
5569 diag::note_pure_virtual_function)
5570 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5571 }
5572 }
5573
5574 if (!PureVirtualClassDiagSet)
5575 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5576 PureVirtualClassDiagSet->insert(RD);
5577}
5578
5579namespace {
5580struct AbstractUsageInfo {
5581 Sema &S;
5582 CXXRecordDecl *Record;
5583 CanQualType AbstractType;
5584 bool Invalid;
5585
5586 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5587 : S(S), Record(Record),
5588 AbstractType(S.Context.getCanonicalType(
5589 S.Context.getTypeDeclType(Record))),
5590 Invalid(false) {}
5591
5592 void DiagnoseAbstractType() {
5593 if (Invalid) return;
5594 S.DiagnoseAbstractType(Record);
5595 Invalid = true;
5596 }
5597
5598 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5599};
5600
5601struct CheckAbstractUsage {
5602 AbstractUsageInfo &Info;
5603 const NamedDecl *Ctx;
5604
5605 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5606 : Info(Info), Ctx(Ctx) {}
5607
5608 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5609 switch (TL.getTypeLocClass()) {
5610#define ABSTRACT_TYPELOC(CLASS, PARENT)
5611#define TYPELOC(CLASS, PARENT) \
5612 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5613#include "clang/AST/TypeLocNodes.def"
5614 }
5615 }
5616
5617 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5618 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5619 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5620 if (!TL.getParam(I))
5621 continue;
5622
5623 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5624 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5625 }
5626 }
5627
5628 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5629 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5630 }
5631
5632 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5633 // Visit the type parameters from a permissive context.
5634 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5635 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5636 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5637 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5638 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5639 // TODO: other template argument types?
5640 }
5641 }
5642
5643 // Visit pointee types from a permissive context.
5644#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5645 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5646 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5647 }
5648 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5649 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5650 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5651 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5652 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5653
5654 /// Handle all the types we haven't given a more specific
5655 /// implementation for above.
5656 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5657 // Every other kind of type that we haven't called out already
5658 // that has an inner type is either (1) sugar or (2) contains that
5659 // inner type in some way as a subobject.
5660 if (TypeLoc Next = TL.getNextTypeLoc())
5661 return Visit(Next, Sel);
5662
5663 // If there's no inner type and we're in a permissive context,
5664 // don't diagnose.
5665 if (Sel == Sema::AbstractNone) return;
5666
5667 // Check whether the type matches the abstract type.
5668 QualType T = TL.getType();
5669 if (T->isArrayType()) {
5670 Sel = Sema::AbstractArrayType;
5671 T = Info.S.Context.getBaseElementType(T);
5672 }
5673 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5674 if (CT != Info.AbstractType) return;
5675
5676 // It matched; do some magic.
5677 if (Sel == Sema::AbstractArrayType) {
5678 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5679 << T << TL.getSourceRange();
5680 } else {
5681 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5682 << Sel << T << TL.getSourceRange();
5683 }
5684 Info.DiagnoseAbstractType();
5685 }
5686};
5687
5688void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5689 Sema::AbstractDiagSelID Sel) {
5690 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5691}
5692
5693}
5694
5695/// Check for invalid uses of an abstract type in a method declaration.
5696static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5697 CXXMethodDecl *MD) {
5698 // No need to do the check on definitions, which require that
5699 // the return/param types be complete.
5700 if (MD->doesThisDeclarationHaveABody())
5701 return;
5702
5703 // For safety's sake, just ignore it if we don't have type source
5704 // information. This should never happen for non-implicit methods,
5705 // but...
5706 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5707 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5708}
5709
5710/// Check for invalid uses of an abstract type within a class definition.
5711static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5712 CXXRecordDecl *RD) {
5713 for (auto *D : RD->decls()) {
5714 if (D->isImplicit()) continue;
5715
5716 // Methods and method templates.
5717 if (isa<CXXMethodDecl>(D)) {
5718 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5719 } else if (isa<FunctionTemplateDecl>(D)) {
5720 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5721 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5722
5723 // Fields and static variables.
5724 } else if (isa<FieldDecl>(D)) {
5725 FieldDecl *FD = cast<FieldDecl>(D);
5726 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5727 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5728 } else if (isa<VarDecl>(D)) {
5729 VarDecl *VD = cast<VarDecl>(D);
5730 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5731 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5732
5733 // Nested classes and class templates.
5734 } else if (isa<CXXRecordDecl>(D)) {
5735 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5736 } else if (isa<ClassTemplateDecl>(D)) {
5737 CheckAbstractClassUsage(Info,
5738 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5739 }
5740 }
5741}
5742
5743static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5744 Attr *ClassAttr = getDLLAttr(Class);
5745 if (!ClassAttr)
5746 return;
5747
5748 assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast<
void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 5748, __PRETTY_FUNCTION__))
;
5749
5750 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5751
5752 if (TSK == TSK_ExplicitInstantiationDeclaration)
5753 // Don't go any further if this is just an explicit instantiation
5754 // declaration.
5755 return;
5756
5757 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5758 S.MarkVTableUsed(Class->getLocation(), Class, true);
5759
5760 for (Decl *Member : Class->decls()) {
5761 // Defined static variables that are members of an exported base
5762 // class must be marked export too.
5763 auto *VD = dyn_cast<VarDecl>(Member);
5764 if (VD && Member->getAttr<DLLExportAttr>() &&
5765 VD->getStorageClass() == SC_Static &&
5766 TSK == TSK_ImplicitInstantiation)
5767 S.MarkVariableReferenced(VD->getLocation(), VD);
5768
5769 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5770 if (!MD)
5771 continue;
5772
5773 if (Member->getAttr<DLLExportAttr>()) {
5774 if (MD->isUserProvided()) {
5775 // Instantiate non-default class member functions ...
5776
5777 // .. except for certain kinds of template specializations.
5778 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5779 continue;
5780
5781 S.MarkFunctionReferenced(Class->getLocation(), MD);
5782
5783 // The function will be passed to the consumer when its definition is
5784 // encountered.
5785 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5786 MD->isCopyAssignmentOperator() ||
5787 MD->isMoveAssignmentOperator()) {
5788 // Synthesize and instantiate non-trivial implicit methods, explicitly
5789 // defaulted methods, and the copy and move assignment operators. The
5790 // latter are exported even if they are trivial, because the address of
5791 // an operator can be taken and should compare equal across libraries.
5792 DiagnosticErrorTrap Trap(S.Diags);
5793 S.MarkFunctionReferenced(Class->getLocation(), MD);
5794 if (Trap.hasErrorOccurred()) {
5795 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5796 << Class << !S.getLangOpts().CPlusPlus11;
5797 break;
5798 }
5799
5800 // There is no later point when we will see the definition of this
5801 // function, so pass it to the consumer now.
5802 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5803 }
5804 }
5805 }
5806}
5807
5808static void checkForMultipleExportedDefaultConstructors(Sema &S,
5809 CXXRecordDecl *Class) {
5810 // Only the MS ABI has default constructor closures, so we don't need to do
5811 // this semantic checking anywhere else.
5812 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5813 return;
5814
5815 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5816 for (Decl *Member : Class->decls()) {
5817 // Look for exported default constructors.
5818 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5819 if (!CD || !CD->isDefaultConstructor())
5820 continue;
5821 auto *Attr = CD->getAttr<DLLExportAttr>();
5822 if (!Attr)
5823 continue;
5824
5825 // If the class is non-dependent, mark the default arguments as ODR-used so
5826 // that we can properly codegen the constructor closure.
5827 if (!Class->isDependentContext()) {
5828 for (ParmVarDecl *PD : CD->parameters()) {
5829 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5830 S.DiscardCleanupsInEvaluationContext();
5831 }
5832 }
5833
5834 if (LastExportedDefaultCtor) {
5835 S.Diag(LastExportedDefaultCtor->getLocation(),
5836 diag::err_attribute_dll_ambiguous_default_ctor)
5837 << Class;
5838 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5839 << CD->getDeclName();
5840 return;
5841 }
5842 LastExportedDefaultCtor = CD;
5843 }
5844}
5845
5846void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5847 // Mark any compiler-generated routines with the implicit code_seg attribute.
5848 for (auto *Method : Class->methods()) {
5849 if (Method->isUserProvided())
5850 continue;
5851 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5852 Method->addAttr(A);
5853 }
5854}
5855
5856/// Check class-level dllimport/dllexport attribute.
5857void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5858 Attr *ClassAttr = getDLLAttr(Class);
5859
5860 // MSVC inherits DLL attributes to partial class template specializations.
5861 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5862 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5863 if (Attr *TemplateAttr =
5864 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5865 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5866 A->setInherited(true);
5867 ClassAttr = A;
5868 }
5869 }
5870 }
5871
5872 if (!ClassAttr)
5873 return;
5874
5875 if (!Class->isExternallyVisible()) {
5876 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5877 << Class << ClassAttr;
5878 return;
5879 }
5880
5881 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5882 !ClassAttr->isInherited()) {
5883 // Diagnose dll attributes on members of class with dll attribute.
5884 for (Decl *Member : Class->decls()) {
5885 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5886 continue;
5887 InheritableAttr *MemberAttr = getDLLAttr(Member);
5888 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5889 continue;
5890
5891 Diag(MemberAttr->getLocation(),
5892 diag::err_attribute_dll_member_of_dll_class)
5893 << MemberAttr << ClassAttr;
5894 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5895 Member->setInvalidDecl();
5896 }
5897 }
5898
5899 if (Class->getDescribedClassTemplate())
5900 // Don't inherit dll attribute until the template is instantiated.
5901 return;
5902
5903 // The class is either imported or exported.
5904 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5905
5906 // Check if this was a dllimport attribute propagated from a derived class to
5907 // a base class template specialization. We don't apply these attributes to
5908 // static data members.
5909 const bool PropagatedImport =
5910 !ClassExported &&
5911 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5912
5913 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5914
5915 // Ignore explicit dllexport on explicit class template instantiation
5916 // declarations, except in MinGW mode.
5917 if (ClassExported && !ClassAttr->isInherited() &&
5918 TSK == TSK_ExplicitInstantiationDeclaration &&
5919 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5920 Class->dropAttr<DLLExportAttr>();
5921 return;
5922 }
5923
5924 // Force declaration of implicit members so they can inherit the attribute.
5925 ForceDeclarationOfImplicitMembers(Class);
5926
5927 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5928 // seem to be true in practice?
5929
5930 for (Decl *Member : Class->decls()) {
5931 VarDecl *VD = dyn_cast<VarDecl>(Member);
5932 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5933
5934 // Only methods and static fields inherit the attributes.
5935 if (!VD && !MD)
5936 continue;
5937
5938 if (MD) {
5939 // Don't process deleted methods.
5940 if (MD->isDeleted())
5941 continue;
5942
5943 if (MD->isInlined()) {
5944 // MinGW does not import or export inline methods. But do it for
5945 // template instantiations.
5946 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5947 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5948 TSK != TSK_ExplicitInstantiationDeclaration &&
5949 TSK != TSK_ExplicitInstantiationDefinition)
5950 continue;
5951
5952 // MSVC versions before 2015 don't export the move assignment operators
5953 // and move constructor, so don't attempt to import/export them if
5954 // we have a definition.
5955 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5956 if ((MD->isMoveAssignmentOperator() ||
5957 (Ctor && Ctor->isMoveConstructor())) &&
5958 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5959 continue;
5960
5961 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5962 // operator is exported anyway.
5963 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5964 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5965 continue;
5966 }
5967 }
5968
5969 // Don't apply dllimport attributes to static data members of class template
5970 // instantiations when the attribute is propagated from a derived class.
5971 if (VD && PropagatedImport)
5972 continue;
5973
5974 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5975 continue;
5976
5977 if (!getDLLAttr(Member)) {
5978 InheritableAttr *NewAttr = nullptr;
5979
5980 // Do not export/import inline function when -fno-dllexport-inlines is
5981 // passed. But add attribute for later local static var check.
5982 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5983 TSK != TSK_ExplicitInstantiationDeclaration &&
5984 TSK != TSK_ExplicitInstantiationDefinition) {
5985 if (ClassExported) {
5986 NewAttr = ::new (getASTContext())
5987 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
5988 } else {
5989 NewAttr = ::new (getASTContext())
5990 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
5991 }
5992 } else {
5993 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5994 }
5995
5996 NewAttr->setInherited(true);
5997 Member->addAttr(NewAttr);
5998
5999 if (MD) {
6000 // Propagate DLLAttr to friend re-declarations of MD that have already
6001 // been constructed.
6002 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6003 FD = FD->getPreviousDecl()) {
6004 if (FD->getFriendObjectKind() == Decl::FOK_None)
6005 continue;
6006 assert(!getDLLAttr(FD) &&((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6007, __PRETTY_FUNCTION__))
6007 "friend re-decl should not already have a DLLAttr")((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6007, __PRETTY_FUNCTION__))
;
6008 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6009 NewAttr->setInherited(true);
6010 FD->addAttr(NewAttr);
6011 }
6012 }
6013 }
6014 }
6015
6016 if (ClassExported)
6017 DelayedDllExportClasses.push_back(Class);
6018}
6019
6020/// Perform propagation of DLL attributes from a derived class to a
6021/// templated base class for MS compatibility.
6022void Sema::propagateDLLAttrToBaseClassTemplate(
6023 CXXRecordDecl *Class, Attr *ClassAttr,
6024 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6025 if (getDLLAttr(
6026 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6027 // If the base class template has a DLL attribute, don't try to change it.
6028 return;
6029 }
6030
6031 auto TSK = BaseTemplateSpec->getSpecializationKind();
6032 if (!getDLLAttr(BaseTemplateSpec) &&
6033 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6034 TSK == TSK_ImplicitInstantiation)) {
6035 // The template hasn't been instantiated yet (or it has, but only as an
6036 // explicit instantiation declaration or implicit instantiation, which means
6037 // we haven't codegenned any members yet), so propagate the attribute.
6038 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6039 NewAttr->setInherited(true);
6040 BaseTemplateSpec->addAttr(NewAttr);
6041
6042 // If this was an import, mark that we propagated it from a derived class to
6043 // a base class template specialization.
6044 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6045 ImportAttr->setPropagatedToBaseTemplate();
6046
6047 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6048 // needs to be run again to work see the new attribute. Otherwise this will
6049 // get run whenever the template is instantiated.
6050 if (TSK != TSK_Undeclared)
6051 checkClassLevelDLLAttribute(BaseTemplateSpec);
6052
6053 return;
6054 }
6055
6056 if (getDLLAttr(BaseTemplateSpec)) {
6057 // The template has already been specialized or instantiated with an
6058 // attribute, explicitly or through propagation. We should not try to change
6059 // it.
6060 return;
6061 }
6062
6063 // The template was previously instantiated or explicitly specialized without
6064 // a dll attribute, It's too late for us to add an attribute, so warn that
6065 // this is unsupported.
6066 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6067 << BaseTemplateSpec->isExplicitSpecialization();
6068 Diag(ClassAttr->getLocation(), diag::note_attribute);
6069 if (BaseTemplateSpec->isExplicitSpecialization()) {
6070 Diag(BaseTemplateSpec->getLocation(),
6071 diag::note_template_class_explicit_specialization_was_here)
6072 << BaseTemplateSpec;
6073 } else {
6074 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6075 diag::note_template_class_instantiation_was_here)
6076 << BaseTemplateSpec;
6077 }
6078}
6079
6080static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
6081 SourceLocation DefaultLoc) {
6082 switch (S.getSpecialMember(MD)) {
6083 case Sema::CXXDefaultConstructor:
6084 S.DefineImplicitDefaultConstructor(DefaultLoc,
6085 cast<CXXConstructorDecl>(MD));
6086 break;
6087 case Sema::CXXCopyConstructor:
6088 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6089 break;
6090 case Sema::CXXCopyAssignment:
6091 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
6092 break;
6093 case Sema::CXXDestructor:
6094 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
6095 break;
6096 case Sema::CXXMoveConstructor:
6097 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6098 break;
6099 case Sema::CXXMoveAssignment:
6100 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
6101 break;
6102 case Sema::CXXInvalid:
6103 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6103)
;
6104 }
6105}
6106
6107/// Determine whether a type is permitted to be passed or returned in
6108/// registers, per C++ [class.temporary]p3.
6109static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6110 TargetInfo::CallingConvKind CCK) {
6111 if (D->isDependentType() || D->isInvalidDecl())
6112 return false;
6113
6114 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6115 // The PS4 platform ABI follows the behavior of Clang 3.2.
6116 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6117 return !D->hasNonTrivialDestructorForCall() &&
6118 !D->hasNonTrivialCopyConstructorForCall();
6119
6120 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6121 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6122 bool DtorIsTrivialForCall = false;
6123
6124 // If a class has at least one non-deleted, trivial copy constructor, it
6125 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6126 //
6127 // Note: This permits classes with non-trivial copy or move ctors to be
6128 // passed in registers, so long as they *also* have a trivial copy ctor,
6129 // which is non-conforming.
6130 if (D->needsImplicitCopyConstructor()) {
6131 if (!D->defaultedCopyConstructorIsDeleted()) {
6132 if (D->hasTrivialCopyConstructor())
6133 CopyCtorIsTrivial = true;
6134 if (D->hasTrivialCopyConstructorForCall())
6135 CopyCtorIsTrivialForCall = true;
6136 }
6137 } else {
6138 for (const CXXConstructorDecl *CD : D->ctors()) {
6139 if (CD->isCopyConstructor() && !CD->isDeleted()) {
6140 if (CD->isTrivial())
6141 CopyCtorIsTrivial = true;
6142 if (CD->isTrivialForCall())
6143 CopyCtorIsTrivialForCall = true;
6144 }
6145 }
6146 }
6147
6148 if (D->needsImplicitDestructor()) {
6149 if (!D->defaultedDestructorIsDeleted() &&
6150 D->hasTrivialDestructorForCall())
6151 DtorIsTrivialForCall = true;
6152 } else if (const auto *DD = D->getDestructor()) {
6153 if (!DD->isDeleted() && DD->isTrivialForCall())
6154 DtorIsTrivialForCall = true;
6155 }
6156
6157 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6158 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6159 return true;
6160
6161 // If a class has a destructor, we'd really like to pass it indirectly
6162 // because it allows us to elide copies. Unfortunately, MSVC makes that
6163 // impossible for small types, which it will pass in a single register or
6164 // stack slot. Most objects with dtors are large-ish, so handle that early.
6165 // We can't call out all large objects as being indirect because there are
6166 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6167 // how we pass large POD types.
6168
6169 // Note: This permits small classes with nontrivial destructors to be
6170 // passed in registers, which is non-conforming.
6171 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6172 uint64_t TypeSize = isAArch64 ? 128 : 64;
6173
6174 if (CopyCtorIsTrivial &&
6175 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6176 return true;
6177 return false;
6178 }
6179
6180 // Per C++ [class.temporary]p3, the relevant condition is:
6181 // each copy constructor, move constructor, and destructor of X is
6182 // either trivial or deleted, and X has at least one non-deleted copy
6183 // or move constructor
6184 bool HasNonDeletedCopyOrMove = false;
6185
6186 if (D->needsImplicitCopyConstructor() &&
6187 !D->defaultedCopyConstructorIsDeleted()) {
6188 if (!D->hasTrivialCopyConstructorForCall())
6189 return false;
6190 HasNonDeletedCopyOrMove = true;
6191 }
6192
6193 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6194 !D->defaultedMoveConstructorIsDeleted()) {
6195 if (!D->hasTrivialMoveConstructorForCall())
6196 return false;
6197 HasNonDeletedCopyOrMove = true;
6198 }
6199
6200 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6201 !D->hasTrivialDestructorForCall())
6202 return false;
6203
6204 for (const CXXMethodDecl *MD : D->methods()) {
6205 if (MD->isDeleted())
6206 continue;
6207
6208 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6209 if (CD && CD->isCopyOrMoveConstructor())
6210 HasNonDeletedCopyOrMove = true;
6211 else if (!isa<CXXDestructorDecl>(MD))
6212 continue;
6213
6214 if (!MD->isTrivialForCall())
6215 return false;
6216 }
6217
6218 return HasNonDeletedCopyOrMove;
6219}
6220
6221/// Perform semantic checks on a class definition that has been
6222/// completing, introducing implicitly-declared members, checking for
6223/// abstract types, etc.
6224void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6225 if (!Record)
6226 return;
6227
6228 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6229 AbstractUsageInfo Info(*this, Record);
6230 CheckAbstractClassUsage(Info, Record);
6231 }
6232
6233 // If this is not an aggregate type and has no user-declared constructor,
6234 // complain about any non-static data members of reference or const scalar
6235 // type, since they will never get initializers.
6236 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6237 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6238 !Record->isLambda()) {
6239 bool Complained = false;
6240 for (const auto *F : Record->fields()) {
6241 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6242 continue;
6243
6244 if (F->getType()->isReferenceType() ||
6245 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6246 if (!Complained) {
6247 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6248 << Record->getTagKind() << Record;
6249 Complained = true;
6250 }
6251
6252 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6253 << F->getType()->isReferenceType()
6254 << F->getDeclName();
6255 }
6256 }
6257 }
6258
6259 if (Record->getIdentifier()) {
6260 // C++ [class.mem]p13:
6261 // If T is the name of a class, then each of the following shall have a
6262 // name different from T:
6263 // - every member of every anonymous union that is a member of class T.
6264 //
6265 // C++ [class.mem]p14:
6266 // In addition, if class T has a user-declared constructor (12.1), every
6267 // non-static data member of class T shall have a name different from T.
6268 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6269 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6270 ++I) {
6271 NamedDecl *D = (*I)->getUnderlyingDecl();
6272 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6273 Record->hasUserDeclaredConstructor()) ||
6274 isa<IndirectFieldDecl>(D)) {
6275 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6276 << D->getDeclName();
6277 break;
6278 }
6279 }
6280 }
6281
6282 // Warn if the class has virtual methods but non-virtual public destructor.
6283 if (Record->isPolymorphic() && !Record->isDependentType()) {
6284 CXXDestructorDecl *dtor = Record->getDestructor();
6285 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6286 !Record->hasAttr<FinalAttr>())
6287 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6288 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6289 }
6290
6291 if (Record->isAbstract()) {
6292 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6293 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6294 << FA->isSpelledAsSealed();
6295 DiagnoseAbstractType(Record);
6296 }
6297 }
6298
6299 // Warn if the class has a final destructor but is not itself marked final.
6300 if (!Record->hasAttr<FinalAttr>()) {
6301 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6302 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6303 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6304 << FA->isSpelledAsSealed()
6305 << FixItHint::CreateInsertion(
6306 getLocForEndOfToken(Record->getLocation()),
6307 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6308 Diag(Record->getLocation(),
6309 diag::note_final_dtor_non_final_class_silence)
6310 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6311 }
6312 }
6313 }
6314
6315 // See if trivial_abi has to be dropped.
6316 if (Record->hasAttr<TrivialABIAttr>())
6317 checkIllFormedTrivialABIStruct(*Record);
6318
6319 // Set HasTrivialSpecialMemberForCall if the record has attribute
6320 // "trivial_abi".
6321 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6322
6323 if (HasTrivialABI)
6324 Record->setHasTrivialSpecialMemberForCall();
6325
6326 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6327 // Check whether the explicitly-defaulted special members are valid.
6328 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6329 CheckExplicitlyDefaultedSpecialMember(M);
6330
6331 // For an explicitly defaulted or deleted special member, we defer
6332 // determining triviality until the class is complete. That time is now!
6333 CXXSpecialMember CSM = getSpecialMember(M);
6334 if (!M->isImplicit() && !M->isUserProvided()) {
6335 if (CSM != CXXInvalid) {
6336 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6337 // Inform the class that we've finished declaring this member.
6338 Record->finishedDefaultedOrDeletedMember(M);
6339 M->setTrivialForCall(
6340 HasTrivialABI ||
6341 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6342 Record->setTrivialForCallFlags(M);
6343 }
6344 }
6345
6346 // Set triviality for the purpose of calls if this is a user-provided
6347 // copy/move constructor or destructor.
6348 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6349 CSM == CXXDestructor) && M->isUserProvided()) {
6350 M->setTrivialForCall(HasTrivialABI);
6351 Record->setTrivialForCallFlags(M);
6352 }
6353
6354 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6355 M->hasAttr<DLLExportAttr>()) {
6356 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6357 M->isTrivial() &&
6358 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6359 CSM == CXXDestructor))
6360 M->dropAttr<DLLExportAttr>();
6361
6362 if (M->hasAttr<DLLExportAttr>()) {
6363 // Define after any fields with in-class initializers have been parsed.
6364 DelayedDllExportMemberFunctions.push_back(M);
6365 }
6366 }
6367
6368 // Define defaulted constexpr virtual functions that override a base class
6369 // function right away.
6370 // FIXME: We can defer doing this until the vtable is marked as used.
6371 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6372 DefineImplicitSpecialMember(*this, M, M->getLocation());
6373 };
6374
6375 bool HasMethodWithOverrideControl = false,
6376 HasOverridingMethodWithoutOverrideControl = false;
6377 if (!Record->isDependentType()) {
6378 // Check the destructor before any other member function. We need to
6379 // determine whether it's trivial in order to determine whether the claas
6380 // type is a literal type, which is a prerequisite for determining whether
6381 // other special member functions are valid and whether they're implicitly
6382 // 'constexpr'.
6383 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6384 CompleteMemberFunction(Dtor);
6385
6386 for (auto *M : Record->methods()) {
6387 // See if a method overloads virtual methods in a base
6388 // class without overriding any.
6389 if (!M->isStatic())
6390 DiagnoseHiddenVirtualMethods(M);
6391 if (M->hasAttr<OverrideAttr>())
6392 HasMethodWithOverrideControl = true;
6393 else if (M->size_overridden_methods() > 0)
6394 HasOverridingMethodWithoutOverrideControl = true;
6395
6396 if (!isa<CXXDestructorDecl>(M))
6397 CompleteMemberFunction(M);
6398 }
6399 }
6400
6401 if (HasMethodWithOverrideControl &&
6402 HasOverridingMethodWithoutOverrideControl) {
6403 // At least one method has the 'override' control declared.
6404 // Diagnose all other overridden methods which do not have 'override' specified on them.
6405 for (auto *M : Record->methods())
6406 DiagnoseAbsenceOfOverrideControl(M);
6407 }
6408
6409 // ms_struct is a request to use the same ABI rules as MSVC. Check
6410 // whether this class uses any C++ features that are implemented
6411 // completely differently in MSVC, and if so, emit a diagnostic.
6412 // That diagnostic defaults to an error, but we allow projects to
6413 // map it down to a warning (or ignore it). It's a fairly common
6414 // practice among users of the ms_struct pragma to mass-annotate
6415 // headers, sweeping up a bunch of types that the project doesn't
6416 // really rely on MSVC-compatible layout for. We must therefore
6417 // support "ms_struct except for C++ stuff" as a secondary ABI.
6418 if (Record->isMsStruct(Context) &&
6419 (Record->isPolymorphic() || Record->getNumBases())) {
6420 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6421 }
6422
6423 checkClassLevelDLLAttribute(Record);
6424 checkClassLevelCodeSegAttribute(Record);
6425
6426 bool ClangABICompat4 =
6427 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6428 TargetInfo::CallingConvKind CCK =
6429 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6430 bool CanPass = canPassInRegisters(*this, Record, CCK);
6431
6432 // Do not change ArgPassingRestrictions if it has already been set to
6433 // APK_CanNeverPassInRegs.
6434 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6435 Record->setArgPassingRestrictions(CanPass
6436 ? RecordDecl::APK_CanPassInRegs
6437 : RecordDecl::APK_CannotPassInRegs);
6438
6439 // If canPassInRegisters returns true despite the record having a non-trivial
6440 // destructor, the record is destructed in the callee. This happens only when
6441 // the record or one of its subobjects has a field annotated with trivial_abi
6442 // or a field qualified with ObjC __strong/__weak.
6443 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6444 Record->setParamDestroyedInCallee(true);
6445 else if (Record->hasNonTrivialDestructor())
6446 Record->setParamDestroyedInCallee(CanPass);
6447
6448 if (getLangOpts().ForceEmitVTables) {
6449 // If we want to emit all the vtables, we need to mark it as used. This
6450 // is especially required for cases like vtable assumption loads.
6451 MarkVTableUsed(Record->getInnerLocStart(), Record);
6452 }
6453}
6454
6455/// Look up the special member function that would be called by a special
6456/// member function for a subobject of class type.
6457///
6458/// \param Class The class type of the subobject.
6459/// \param CSM The kind of special member function.
6460/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6461/// \param ConstRHS True if this is a copy operation with a const object
6462/// on its RHS, that is, if the argument to the outer special member
6463/// function is 'const' and this is not a field marked 'mutable'.
6464static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6465 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6466 unsigned FieldQuals, bool ConstRHS) {
6467 unsigned LHSQuals = 0;
6468 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6469 LHSQuals = FieldQuals;
6470
6471 unsigned RHSQuals = FieldQuals;
6472 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6473 RHSQuals = 0;
6474 else if (ConstRHS)
6475 RHSQuals |= Qualifiers::Const;
6476
6477 return S.LookupSpecialMember(Class, CSM,
6478 RHSQuals & Qualifiers::Const,
6479 RHSQuals & Qualifiers::Volatile,
6480 false,
6481 LHSQuals & Qualifiers::Const,
6482 LHSQuals & Qualifiers::Volatile);
6483}
6484
6485class Sema::InheritedConstructorInfo {
6486 Sema &S;
6487 SourceLocation UseLoc;
6488
6489 /// A mapping from the base classes through which the constructor was
6490 /// inherited to the using shadow declaration in that base class (or a null
6491 /// pointer if the constructor was declared in that base class).
6492 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6493 InheritedFromBases;
6494
6495public:
6496 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6497 ConstructorUsingShadowDecl *Shadow)
6498 : S(S), UseLoc(UseLoc) {
6499 bool DiagnosedMultipleConstructedBases = false;
6500 CXXRecordDecl *ConstructedBase = nullptr;
6501 UsingDecl *ConstructedBaseUsing = nullptr;
6502
6503 // Find the set of such base class subobjects and check that there's a
6504 // unique constructed subobject.
6505 for (auto *D : Shadow->redecls()) {
6506 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6507 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6508 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6509
6510 InheritedFromBases.insert(
6511 std::make_pair(DNominatedBase->getCanonicalDecl(),
6512 DShadow->getNominatedBaseClassShadowDecl()));
6513 if (DShadow->constructsVirtualBase())
6514 InheritedFromBases.insert(
6515 std::make_pair(DConstructedBase->getCanonicalDecl(),
6516 DShadow->getConstructedBaseClassShadowDecl()));
6517 else
6518 assert(DNominatedBase == DConstructedBase)((DNominatedBase == DConstructedBase) ? static_cast<void>
(0) : __assert_fail ("DNominatedBase == DConstructedBase", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6518, __PRETTY_FUNCTION__))
;
6519
6520 // [class.inhctor.init]p2:
6521 // If the constructor was inherited from multiple base class subobjects
6522 // of type B, the program is ill-formed.
6523 if (!ConstructedBase) {
6524 ConstructedBase = DConstructedBase;
6525 ConstructedBaseUsing = D->getUsingDecl();
6526 } else if (ConstructedBase != DConstructedBase &&
6527 !Shadow->isInvalidDecl()) {
6528 if (!DiagnosedMultipleConstructedBases) {
6529 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6530 << Shadow->getTargetDecl();
6531 S.Diag(ConstructedBaseUsing->getLocation(),
6532 diag::note_ambiguous_inherited_constructor_using)
6533 << ConstructedBase;
6534 DiagnosedMultipleConstructedBases = true;
6535 }
6536 S.Diag(D->getUsingDecl()->getLocation(),
6537 diag::note_ambiguous_inherited_constructor_using)
6538 << DConstructedBase;
6539 }
6540 }
6541
6542 if (DiagnosedMultipleConstructedBases)
6543 Shadow->setInvalidDecl();
6544 }
6545
6546 /// Find the constructor to use for inherited construction of a base class,
6547 /// and whether that base class constructor inherits the constructor from a
6548 /// virtual base class (in which case it won't actually invoke it).
6549 std::pair<CXXConstructorDecl *, bool>
6550 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6551 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6552 if (It == InheritedFromBases.end())
6553 return std::make_pair(nullptr, false);
6554
6555 // This is an intermediary class.
6556 if (It->second)
6557 return std::make_pair(
6558 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6559 It->second->constructsVirtualBase());
6560
6561 // This is the base class from which the constructor was inherited.
6562 return std::make_pair(Ctor, false);
6563 }
6564};
6565
6566/// Is the special member function which would be selected to perform the
6567/// specified operation on the specified class type a constexpr constructor?
6568static bool
6569specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6570 Sema::CXXSpecialMember CSM, unsigned Quals,
6571 bool ConstRHS,
6572 CXXConstructorDecl *InheritedCtor = nullptr,
6573 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6574 // If we're inheriting a constructor, see if we need to call it for this base
6575 // class.
6576 if (InheritedCtor) {
6577 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6577, __PRETTY_FUNCTION__))
;
6578 auto BaseCtor =
6579 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6580 if (BaseCtor)
6581 return BaseCtor->isConstexpr();
6582 }
6583
6584 if (CSM == Sema::CXXDefaultConstructor)
6585 return ClassDecl->hasConstexprDefaultConstructor();
6586 if (CSM == Sema::CXXDestructor)
6587 return ClassDecl->hasConstexprDestructor();
6588
6589 Sema::SpecialMemberOverloadResult SMOR =
6590 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6591 if (!SMOR.getMethod())
6592 // A constructor we wouldn't select can't be "involved in initializing"
6593 // anything.
6594 return true;
6595 return SMOR.getMethod()->isConstexpr();
6596}
6597
6598/// Determine whether the specified special member function would be constexpr
6599/// if it were implicitly defined.
6600static bool defaultedSpecialMemberIsConstexpr(
6601 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6602 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6603 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6604 if (!S.getLangOpts().CPlusPlus11)
6605 return false;
6606
6607 // C++11 [dcl.constexpr]p4:
6608 // In the definition of a constexpr constructor [...]
6609 bool Ctor = true;
6610 switch (CSM) {
6611 case Sema::CXXDefaultConstructor:
6612 if (Inherited)
6613 break;
6614 // Since default constructor lookup is essentially trivial (and cannot
6615 // involve, for instance, template instantiation), we compute whether a
6616 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6617 //
6618 // This is important for performance; we need to know whether the default
6619 // constructor is constexpr to determine whether the type is a literal type.
6620 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6621
6622 case Sema::CXXCopyConstructor:
6623 case Sema::CXXMoveConstructor:
6624 // For copy or move constructors, we need to perform overload resolution.
6625 break;
6626
6627 case Sema::CXXCopyAssignment:
6628 case Sema::CXXMoveAssignment:
6629 if (!S.getLangOpts().CPlusPlus14)
6630 return false;
6631 // In C++1y, we need to perform overload resolution.
6632 Ctor = false;
6633 break;
6634
6635 case Sema::CXXDestructor:
6636 return ClassDecl->defaultedDestructorIsConstexpr();
6637
6638 case Sema::CXXInvalid:
6639 return false;
6640 }
6641
6642 // -- if the class is a non-empty union, or for each non-empty anonymous
6643 // union member of a non-union class, exactly one non-static data member
6644 // shall be initialized; [DR1359]
6645 //
6646 // If we squint, this is guaranteed, since exactly one non-static data member
6647 // will be initialized (if the constructor isn't deleted), we just don't know
6648 // which one.
6649 if (Ctor && ClassDecl->isUnion())
6650 return CSM == Sema::CXXDefaultConstructor
6651 ? ClassDecl->hasInClassInitializer() ||
6652 !ClassDecl->hasVariantMembers()
6653 : true;
6654
6655 // -- the class shall not have any virtual base classes;
6656 if (Ctor && ClassDecl->getNumVBases())
6657 return false;
6658
6659 // C++1y [class.copy]p26:
6660 // -- [the class] is a literal type, and
6661 if (!Ctor && !ClassDecl->isLiteral())
6662 return false;
6663
6664 // -- every constructor involved in initializing [...] base class
6665 // sub-objects shall be a constexpr constructor;
6666 // -- the assignment operator selected to copy/move each direct base
6667 // class is a constexpr function, and
6668 for (const auto &B : ClassDecl->bases()) {
6669 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6670 if (!BaseType) continue;
6671
6672 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6673 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6674 InheritedCtor, Inherited))
6675 return false;
6676 }
6677
6678 // -- every constructor involved in initializing non-static data members
6679 // [...] shall be a constexpr constructor;
6680 // -- every non-static data member and base class sub-object shall be
6681 // initialized
6682 // -- for each non-static data member of X that is of class type (or array
6683 // thereof), the assignment operator selected to copy/move that member is
6684 // a constexpr function
6685 for (const auto *F : ClassDecl->fields()) {
6686 if (F->isInvalidDecl())
6687 continue;
6688 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6689 continue;
6690 QualType BaseType = S.Context.getBaseElementType(F->getType());
6691 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6692 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6693 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6694 BaseType.getCVRQualifiers(),
6695 ConstArg && !F->isMutable()))
6696 return false;
6697 } else if (CSM == Sema::CXXDefaultConstructor) {
6698 return false;
6699 }
6700 }
6701
6702 // All OK, it's constexpr!
6703 return true;
6704}
6705
6706static Sema::ImplicitExceptionSpecification
6707ComputeDefaultedSpecialMemberExceptionSpec(
6708 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6709 Sema::InheritedConstructorInfo *ICI);
6710
6711static Sema::ImplicitExceptionSpecification
6712computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6713 auto CSM = S.getSpecialMember(MD);
6714 if (CSM != Sema::CXXInvalid)
6715 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6716
6717 auto *CD = cast<CXXConstructorDecl>(MD);
6718 assert(CD->getInheritedConstructor() &&((CD->getInheritedConstructor() && "only special members have implicit exception specs"
) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6719, __PRETTY_FUNCTION__))
6719 "only special members have implicit exception specs")((CD->getInheritedConstructor() && "only special members have implicit exception specs"
) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6719, __PRETTY_FUNCTION__))
;
6720 Sema::InheritedConstructorInfo ICI(
6721 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6722 return ComputeDefaultedSpecialMemberExceptionSpec(
6723 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6724}
6725
6726static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6727 CXXMethodDecl *MD) {
6728 FunctionProtoType::ExtProtoInfo EPI;
6729
6730 // Build an exception specification pointing back at this member.
6731 EPI.ExceptionSpec.Type = EST_Unevaluated;
6732 EPI.ExceptionSpec.SourceDecl = MD;
6733
6734 // Set the calling convention to the default for C++ instance methods.
6735 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6736 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6737 /*IsCXXMethod=*/true));
6738 return EPI;
6739}
6740
6741void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6742 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6743 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6744 return;
6745
6746 // Evaluate the exception specification.
6747 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6748 auto ESI = IES.getExceptionSpec();
6749
6750 // Update the type of the special member to use it.
6751 UpdateExceptionSpec(MD, ESI);
6752
6753 // A user-provided destructor can be defined outside the class. When that
6754 // happens, be sure to update the exception specification on both
6755 // declarations.
6756 const FunctionProtoType *CanonicalFPT =
6757 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6758 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6759 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6760}
6761
6762void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6763 CXXRecordDecl *RD = MD->getParent();
6764 CXXSpecialMember CSM = getSpecialMember(MD);
6765
6766 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6767, __PRETTY_FUNCTION__))
6767 "not an explicitly-defaulted special member")((MD->isExplicitlyDefaulted() && CSM != CXXInvalid
&& "not an explicitly-defaulted special member") ? static_cast
<void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6767, __PRETTY_FUNCTION__))
;
6768
6769 // Whether this was the first-declared instance of the constructor.
6770 // This affects whether we implicitly add an exception spec and constexpr.
6771 bool First = MD == MD->getCanonicalDecl();
6772
6773 bool HadError = false;
6774
6775 // C++11 [dcl.fct.def.default]p1:
6776 // A function that is explicitly defaulted shall
6777 // -- be a special member function (checked elsewhere),
6778 // -- have the same type (except for ref-qualifiers, and except that a
6779 // copy operation can take a non-const reference) as an implicit
6780 // declaration, and
6781 // -- not have default arguments.
6782 // C++2a changes the second bullet to instead delete the function if it's
6783 // defaulted on its first declaration, unless it's "an assignment operator,
6784 // and its return type differs or its parameter type is not a reference".
6785 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6786 bool ShouldDeleteForTypeMismatch = false;
6787 unsigned ExpectedParams = 1;
6788 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6789 ExpectedParams = 0;
6790 if (MD->getNumParams() != ExpectedParams) {
6791 // This checks for default arguments: a copy or move constructor with a
6792 // default argument is classified as a default constructor, and assignment
6793 // operations and destructors can't have default arguments.
6794 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6795 << CSM << MD->getSourceRange();
6796 HadError = true;
6797 } else if (MD->isVariadic()) {
6798 if (DeleteOnTypeMismatch)
6799 ShouldDeleteForTypeMismatch = true;
6800 else {
6801 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6802 << CSM << MD->getSourceRange();
6803 HadError = true;
6804 }
6805 }
6806
6807 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6808
6809 bool CanHaveConstParam = false;
6810 if (CSM == CXXCopyConstructor)
6811 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6812 else if (CSM == CXXCopyAssignment)
6813 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6814
6815 QualType ReturnType = Context.VoidTy;
6816 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6817 // Check for return type matching.
6818 ReturnType = Type->getReturnType();
6819
6820 QualType DeclType = Context.getTypeDeclType(RD);
6821 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6822 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6823
6824 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6825 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6826 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6827 HadError = true;
6828 }
6829
6830 // A defaulted special member cannot have cv-qualifiers.
6831 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6832 if (DeleteOnTypeMismatch)
6833 ShouldDeleteForTypeMismatch = true;
6834 else {
6835 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6836 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6837 HadError = true;
6838 }
6839 }
6840 }
6841
6842 // Check for parameter type matching.
6843 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6844 bool HasConstParam = false;
6845 if (ExpectedParams && ArgType->isReferenceType()) {
6846 // Argument must be reference to possibly-const T.
6847 QualType ReferentType = ArgType->getPointeeType();
6848 HasConstParam = ReferentType.isConstQualified();
6849
6850 if (ReferentType.isVolatileQualified()) {
6851 if (DeleteOnTypeMismatch)
6852 ShouldDeleteForTypeMismatch = true;
6853 else {
6854 Diag(MD->getLocation(),
6855 diag::err_defaulted_special_member_volatile_param) << CSM;
6856 HadError = true;
6857 }
6858 }
6859
6860 if (HasConstParam && !CanHaveConstParam) {
6861 if (DeleteOnTypeMismatch)
6862 ShouldDeleteForTypeMismatch = true;
6863 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6864 Diag(MD->getLocation(),
6865 diag::err_defaulted_special_member_copy_const_param)
6866 << (CSM == CXXCopyAssignment);
6867 // FIXME: Explain why this special member can't be const.
6868 HadError = true;
6869 } else {
6870 Diag(MD->getLocation(),
6871 diag::err_defaulted_special_member_move_const_param)
6872 << (CSM == CXXMoveAssignment);
6873 HadError = true;
6874 }
6875 }
6876 } else if (ExpectedParams) {
6877 // A copy assignment operator can take its argument by value, but a
6878 // defaulted one cannot.
6879 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")((CSM == CXXCopyAssignment && "unexpected non-ref argument"
) ? static_cast<void> (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6879, __PRETTY_FUNCTION__))
;
6880 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6881 HadError = true;
6882 }
6883
6884 // C++11 [dcl.fct.def.default]p2:
6885 // An explicitly-defaulted function may be declared constexpr only if it
6886 // would have been implicitly declared as constexpr,
6887 // Do not apply this rule to members of class templates, since core issue 1358
6888 // makes such functions always instantiate to constexpr functions. For
6889 // functions which cannot be constexpr (for non-constructors in C++11 and for
6890 // destructors in C++14 and C++17), this is checked elsewhere.
6891 //
6892 // FIXME: This should not apply if the member is deleted.
6893 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6894 HasConstParam);
6895 if ((getLangOpts().CPlusPlus2a ||
6896 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6897 : isa<CXXConstructorDecl>(MD))) &&
6898 MD->isConstexpr() && !Constexpr &&
6899 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6900 Diag(MD->getBeginLoc(), MD->isConsteval()
6901 ? diag::err_incorrect_defaulted_consteval
6902 : diag::err_incorrect_defaulted_constexpr)
6903 << CSM;
6904 // FIXME: Explain why the special member can't be constexpr.
6905 HadError = true;
6906 }
6907
6908 if (First) {
6909 // C++2a [dcl.fct.def.default]p3:
6910 // If a function is explicitly defaulted on its first declaration, it is
6911 // implicitly considered to be constexpr if the implicit declaration
6912 // would be.
6913 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6914
6915 if (!Type->hasExceptionSpec()) {
6916 // C++2a [except.spec]p3:
6917 // If a declaration of a function does not have a noexcept-specifier
6918 // [and] is defaulted on its first declaration, [...] the exception
6919 // specification is as specified below
6920 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6921 EPI.ExceptionSpec.Type = EST_Unevaluated;
6922 EPI.ExceptionSpec.SourceDecl = MD;
6923 MD->setType(Context.getFunctionType(ReturnType,
6924 llvm::makeArrayRef(&ArgType,
6925 ExpectedParams),
6926 EPI));
6927 }
6928 }
6929
6930 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6931 if (First) {
6932 SetDeclDeleted(MD, MD->getLocation());
6933 if (!inTemplateInstantiation() && !HadError) {
6934 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6935 if (ShouldDeleteForTypeMismatch) {
6936 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6937 } else {
6938 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6939 }
6940 }
6941 if (ShouldDeleteForTypeMismatch && !HadError) {
6942 Diag(MD->getLocation(),
6943 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6944 }
6945 } else {
6946 // C++11 [dcl.fct.def.default]p4:
6947 // [For a] user-provided explicitly-defaulted function [...] if such a
6948 // function is implicitly defined as deleted, the program is ill-formed.
6949 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6950 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")((!ShouldDeleteForTypeMismatch && "deleted non-first decl"
) ? static_cast<void> (0) : __assert_fail ("!ShouldDeleteForTypeMismatch && \"deleted non-first decl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 6950, __PRETTY_FUNCTION__))
;
6951 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6952 HadError = true;
6953 }
6954 }
6955
6956 if (HadError)
6957 MD->setInvalidDecl();
6958}
6959
6960void Sema::CheckDelayedMemberExceptionSpecs() {
6961 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6962 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6963
6964 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6965 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6966
6967 // Perform any deferred checking of exception specifications for virtual
6968 // destructors.
6969 for (auto &Check : Overriding)
6970 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6971
6972 // Perform any deferred checking of exception specifications for befriended
6973 // special members.
6974 for (auto &Check : Equivalent)
6975 CheckEquivalentExceptionSpec(Check.second, Check.first);
6976}
6977
6978namespace {
6979/// CRTP base class for visiting operations performed by a special member
6980/// function (or inherited constructor).
6981template<typename Derived>
6982struct SpecialMemberVisitor {
6983 Sema &S;
6984 CXXMethodDecl *MD;
6985 Sema::CXXSpecialMember CSM;
6986 Sema::InheritedConstructorInfo *ICI;
6987
6988 // Properties of the special member, computed for convenience.
6989 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6990
6991 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6992 Sema::InheritedConstructorInfo *ICI)
6993 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6994 switch (CSM) {
6995 case Sema::CXXDefaultConstructor:
6996 case Sema::CXXCopyConstructor:
6997 case Sema::CXXMoveConstructor:
6998 IsConstructor = true;
6999 break;
7000 case Sema::CXXCopyAssignment:
7001 case Sema::CXXMoveAssignment:
7002 IsAssignment = true;
7003 break;
7004 case Sema::CXXDestructor:
7005 break;
7006 case Sema::CXXInvalid:
7007 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7007)
;
7008 }
7009
7010 if (MD->getNumParams()) {
7011 if (const ReferenceType *RT =
7012 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
7013 ConstArg = RT->getPointeeType().isConstQualified();
7014 }
7015 }
7016
7017 Derived &getDerived() { return static_cast<Derived&>(*this); }
7018
7019 /// Is this a "move" special member?
7020 bool isMove() const {
7021 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
7022 }
7023
7024 /// Look up the corresponding special member in the given class.
7025 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
7026 unsigned Quals, bool IsMutable) {
7027 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
7028 ConstArg && !IsMutable);
7029 }
7030
7031 /// Look up the constructor for the specified base class to see if it's
7032 /// overridden due to this being an inherited constructor.
7033 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
7034 if (!ICI)
7035 return {};
7036 assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void>
(0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7036, __PRETTY_FUNCTION__))
;
7037 auto *BaseCtor =
7038 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
7039 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
7040 return MD;
7041 return {};
7042 }
7043
7044 /// A base or member subobject.
7045 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
7046
7047 /// Get the location to use for a subobject in diagnostics.
7048 static SourceLocation getSubobjectLoc(Subobject Subobj) {
7049 // FIXME: For an indirect virtual base, the direct base leading to
7050 // the indirect virtual base would be a more useful choice.
7051 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
7052 return B->getBaseTypeLoc();
7053 else
7054 return Subobj.get<FieldDecl*>()->getLocation();
7055 }
7056
7057 enum BasesToVisit {
7058 /// Visit all non-virtual (direct) bases.
7059 VisitNonVirtualBases,
7060 /// Visit all direct bases, virtual or not.
7061 VisitDirectBases,
7062 /// Visit all non-virtual bases, and all virtual bases if the class
7063 /// is not abstract.
7064 VisitPotentiallyConstructedBases,
7065 /// Visit all direct or virtual bases.
7066 VisitAllBases
7067 };
7068
7069 // Visit the bases and members of the class.
7070 bool visit(BasesToVisit Bases) {
7071 CXXRecordDecl *RD = MD->getParent();
7072
7073 if (Bases == VisitPotentiallyConstructedBases)
7074 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
7075
7076 for (auto &B : RD->bases())
7077 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
7078 getDerived().visitBase(&B))
7079 return true;
7080
7081 if (Bases == VisitAllBases)
7082 for (auto &B : RD->vbases())
7083 if (getDerived().visitBase(&B))
7084 return true;
7085
7086 for (auto *F : RD->fields())
7087 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
7088 getDerived().visitField(F))
7089 return true;
7090
7091 return false;
7092 }
7093};
7094}
7095
7096namespace {
7097struct SpecialMemberDeletionInfo
7098 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
7099 bool Diagnose;
7100
7101 SourceLocation Loc;
7102
7103 bool AllFieldsAreConst;
7104
7105 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
7106 Sema::CXXSpecialMember CSM,
7107 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
7108 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
7109 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
7110
7111 bool inUnion() const { return MD->getParent()->isUnion(); }
7112
7113 Sema::CXXSpecialMember getEffectiveCSM() {
7114 return ICI ? Sema::CXXInvalid : CSM;
7115 }
7116
7117 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
7118
7119 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
7120 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
7121
7122 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
7123 bool shouldDeleteForField(FieldDecl *FD);
7124 bool shouldDeleteForAllConstMembers();
7125
7126 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
7127 unsigned Quals);
7128 bool shouldDeleteForSubobjectCall(Subobject Subobj,
7129 Sema::SpecialMemberOverloadResult SMOR,
7130 bool IsDtorCallInCtor);
7131
7132 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
7133};
7134}
7135
7136/// Is the given special member inaccessible when used on the given
7137/// sub-object.
7138bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
7139 CXXMethodDecl *target) {
7140 /// If we're operating on a base class, the object type is the
7141 /// type of this special member.
7142 QualType objectTy;
7143 AccessSpecifier access = target->getAccess();
7144 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
7145 objectTy = S.Context.getTypeDeclType(MD->getParent());
7146 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
7147
7148 // If we're operating on a field, the object type is the type of the field.
7149 } else {
7150 objectTy = S.Context.getTypeDeclType(target->getParent());
7151 }
7152
7153 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
7154}
7155
7156/// Check whether we should delete a special member due to the implicit
7157/// definition containing a call to a special member of a subobject.
7158bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
7159 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
7160 bool IsDtorCallInCtor) {
7161 CXXMethodDecl *Decl = SMOR.getMethod();
7162 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7163
7164 int DiagKind = -1;
7165
7166 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
7167 DiagKind = !Decl ? 0 : 1;
7168 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7169 DiagKind = 2;
7170 else if (!isAccessible(Subobj, Decl))
7171 DiagKind = 3;
7172 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
7173 !Decl->isTrivial()) {
7174 // A member of a union must have a trivial corresponding special member.
7175 // As a weird special case, a destructor call from a union's constructor
7176 // must be accessible and non-deleted, but need not be trivial. Such a
7177 // destructor is never actually called, but is semantically checked as
7178 // if it were.
7179 DiagKind = 4;
7180 }
7181
7182 if (DiagKind == -1)
7183 return false;
7184
7185 if (Diagnose) {
7186 if (Field) {
7187 S.Diag(Field->getLocation(),
7188 diag::note_deleted_special_member_class_subobject)
7189 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
7190 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
7191 } else {
7192 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
7193 S.Diag(Base->getBeginLoc(),
7194 diag::note_deleted_special_member_class_subobject)
7195 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7196 << Base->getType() << DiagKind << IsDtorCallInCtor
7197 << /*IsObjCPtr*/false;
7198 }
7199
7200 if (DiagKind == 1)
7201 S.NoteDeletedFunction(Decl);
7202 // FIXME: Explain inaccessibility if DiagKind == 3.
7203 }
7204
7205 return true;
7206}
7207
7208/// Check whether we should delete a special member function due to having a
7209/// direct or virtual base class or non-static data member of class type M.
7210bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7211 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7212 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7213 bool IsMutable = Field && Field->isMutable();
7214
7215 // C++11 [class.ctor]p5:
7216 // -- any direct or virtual base class, or non-static data member with no
7217 // brace-or-equal-initializer, has class type M (or array thereof) and
7218 // either M has no default constructor or overload resolution as applied
7219 // to M's default constructor results in an ambiguity or in a function
7220 // that is deleted or inaccessible
7221 // C++11 [class.copy]p11, C++11 [class.copy]p23:
7222 // -- a direct or virtual base class B that cannot be copied/moved because
7223 // overload resolution, as applied to B's corresponding special member,
7224 // results in an ambiguity or a function that is deleted or inaccessible
7225 // from the defaulted special member
7226 // C++11 [class.dtor]p5:
7227 // -- any direct or virtual base class [...] has a type with a destructor
7228 // that is deleted or inaccessible
7229 if (!(CSM == Sema::CXXDefaultConstructor &&
7230 Field && Field->hasInClassInitializer()) &&
7231 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7232 false))
7233 return true;
7234
7235 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7236 // -- any direct or virtual base class or non-static data member has a
7237 // type with a destructor that is deleted or inaccessible
7238 if (IsConstructor) {
7239 Sema::SpecialMemberOverloadResult SMOR =
7240 S.LookupSpecialMember(Class, Sema::CXXDestructor,
7241 false, false, false, false, false);
7242 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7243 return true;
7244 }
7245
7246 return false;
7247}
7248
7249bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7250 FieldDecl *FD, QualType FieldType) {
7251 // The defaulted special functions are defined as deleted if this is a variant
7252 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7253 // type under ARC.
7254 if (!FieldType.hasNonTrivialObjCLifetime())
7255 return false;
7256
7257 // Don't make the defaulted default constructor defined as deleted if the
7258 // member has an in-class initializer.
7259 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7260 return false;
7261
7262 if (Diagnose) {
7263 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7264 S.Diag(FD->getLocation(),
7265 diag::note_deleted_special_member_class_subobject)
7266 << getEffectiveCSM() << ParentClass << /*IsField*/true
7267 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7268 }
7269
7270 return true;
7271}
7272
7273/// Check whether we should delete a special member function due to the class
7274/// having a particular direct or virtual base class.
7275bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7276 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7277 // If program is correct, BaseClass cannot be null, but if it is, the error
7278 // must be reported elsewhere.
7279 if (!BaseClass)
7280 return false;
7281 // If we have an inheriting constructor, check whether we're calling an
7282 // inherited constructor instead of a default constructor.
7283 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7284 if (auto *BaseCtor = SMOR.getMethod()) {
7285 // Note that we do not check access along this path; other than that,
7286 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7287 // FIXME: Check that the base has a usable destructor! Sink this into
7288 // shouldDeleteForClassSubobject.
7289 if (BaseCtor->isDeleted() && Diagnose) {
7290 S.Diag(Base->getBeginLoc(),
7291 diag::note_deleted_special_member_class_subobject)
7292 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7293 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7294 << /*IsObjCPtr*/false;
7295 S.NoteDeletedFunction(BaseCtor);
7296 }
7297 return BaseCtor->isDeleted();
7298 }
7299 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7300}
7301
7302/// Check whether we should delete a special member function due to the class
7303/// having a particular non-static data member.
7304bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7305 QualType FieldType = S.Context.getBaseElementType(FD->getType());
7306 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7307
7308 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7309 return true;
7310
7311 if (CSM == Sema::CXXDefaultConstructor) {
7312 // For a default constructor, all references must be initialized in-class
7313 // and, if a union, it must have a non-const member.
7314 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7315 if (Diagnose)
7316 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7317 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7318 return true;
7319 }
7320 // C++11 [class.ctor]p5: any non-variant non-static data member of
7321 // const-qualified type (or array thereof) with no
7322 // brace-or-equal-initializer does not have a user-provided default
7323 // constructor.
7324 if (!inUnion() && FieldType.isConstQualified() &&
7325 !FD->hasInClassInitializer() &&
7326 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7327 if (Diagnose)
7328 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7329 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7330 return true;
7331 }
7332
7333 if (inUnion() && !FieldType.isConstQualified())
7334 AllFieldsAreConst = false;
7335 } else if (CSM == Sema::CXXCopyConstructor) {
7336 // For a copy constructor, data members must not be of rvalue reference
7337 // type.
7338 if (FieldType->isRValueReferenceType()) {
7339 if (Diagnose)
7340 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7341 << MD->getParent() << FD << FieldType;
7342 return true;
7343 }
7344 } else if (IsAssignment) {
7345 // For an assignment operator, data members must not be of reference type.
7346 if (FieldType->isReferenceType()) {
7347 if (Diagnose)
7348 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7349 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7350 return true;
7351 }
7352 if (!FieldRecord && FieldType.isConstQualified()) {
7353 // C++11 [class.copy]p23:
7354 // -- a non-static data member of const non-class type (or array thereof)
7355 if (Diagnose)
7356 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7357 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7358 return true;
7359 }
7360 }
7361
7362 if (FieldRecord) {
7363 // Some additional restrictions exist on the variant members.
7364 if (!inUnion() && FieldRecord->isUnion() &&
7365 FieldRecord->isAnonymousStructOrUnion()) {
7366 bool AllVariantFieldsAreConst = true;
7367
7368 // FIXME: Handle anonymous unions declared within anonymous unions.
7369 for (auto *UI : FieldRecord->fields()) {
7370 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7371
7372 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7373 return true;
7374
7375 if (!UnionFieldType.isConstQualified())
7376 AllVariantFieldsAreConst = false;
7377
7378 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7379 if (UnionFieldRecord &&
7380 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7381 UnionFieldType.getCVRQualifiers()))
7382 return true;
7383 }
7384
7385 // At least one member in each anonymous union must be non-const
7386 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7387 !FieldRecord->field_empty()) {
7388 if (Diagnose)
7389 S.Diag(FieldRecord->getLocation(),
7390 diag::note_deleted_default_ctor_all_const)
7391 << !!ICI << MD->getParent() << /*anonymous union*/1;
7392 return true;
7393 }
7394
7395 // Don't check the implicit member of the anonymous union type.
7396 // This is technically non-conformant, but sanity demands it.
7397 return false;
7398 }
7399
7400 if (shouldDeleteForClassSubobject(FieldRecord, FD,
7401 FieldType.getCVRQualifiers()))
7402 return true;
7403 }
7404
7405 return false;
7406}
7407
7408/// C++11 [class.ctor] p5:
7409/// A defaulted default constructor for a class X is defined as deleted if
7410/// X is a union and all of its variant members are of const-qualified type.
7411bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7412 // This is a silly definition, because it gives an empty union a deleted
7413 // default constructor. Don't do that.
7414 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7415 bool AnyFields = false;
7416 for (auto *F : MD->getParent()->fields())
7417 if ((AnyFields = !F->isUnnamedBitfield()))
7418 break;
7419 if (!AnyFields)
7420 return false;
7421 if (Diagnose)
7422 S.Diag(MD->getParent()->getLocation(),
7423 diag::note_deleted_default_ctor_all_const)
7424 << !!ICI << MD->getParent() << /*not anonymous union*/0;
7425 return true;
7426 }
7427 return false;
7428}
7429
7430/// Determine whether a defaulted special member function should be defined as
7431/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7432/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7433bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7434 InheritedConstructorInfo *ICI,
7435 bool Diagnose) {
7436 if (MD->isInvalidDecl())
7437 return false;
7438 CXXRecordDecl *RD = MD->getParent();
7439 assert(!RD->isDependentType() && "do deletion after instantiation")((!RD->isDependentType() && "do deletion after instantiation"
) ? static_cast<void> (0) : __assert_fail ("!RD->isDependentType() && \"do deletion after instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7439, __PRETTY_FUNCTION__))
;
7440 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7441 return false;
7442
7443 // C++11 [expr.lambda.prim]p19:
7444 // The closure type associated with a lambda-expression has a
7445 // deleted (8.4.3) default constructor and a deleted copy
7446 // assignment operator.
7447 // C++2a adds back these operators if the lambda has no lambda-capture.
7448 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7449 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7450 if (Diagnose)
7451 Diag(RD->getLocation(), diag::note_lambda_decl);
7452 return true;
7453 }
7454
7455 // For an anonymous struct or union, the copy and assignment special members
7456 // will never be used, so skip the check. For an anonymous union declared at
7457 // namespace scope, the constructor and destructor are used.
7458 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7459 RD->isAnonymousStructOrUnion())
7460 return false;
7461
7462 // C++11 [class.copy]p7, p18:
7463 // If the class definition declares a move constructor or move assignment
7464 // operator, an implicitly declared copy constructor or copy assignment
7465 // operator is defined as deleted.
7466 if (MD->isImplicit() &&
7467 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7468 CXXMethodDecl *UserDeclaredMove = nullptr;
7469
7470 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7471 // deletion of the corresponding copy operation, not both copy operations.
7472 // MSVC 2015 has adopted the standards conforming behavior.
7473 bool DeletesOnlyMatchingCopy =
7474 getLangOpts().MSVCCompat &&
7475 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7476
7477 if (RD->hasUserDeclaredMoveConstructor() &&
7478 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7479 if (!Diagnose) return true;
7480
7481 // Find any user-declared move constructor.
7482 for (auto *I : RD->ctors()) {
7483 if (I->isMoveConstructor()) {
7484 UserDeclaredMove = I;
7485 break;
7486 }
7487 }
7488 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7488, __PRETTY_FUNCTION__))
;
7489 } else if (RD->hasUserDeclaredMoveAssignment() &&
7490 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7491 if (!Diagnose) return true;
7492
7493 // Find any user-declared move assignment operator.
7494 for (auto *I : RD->methods()) {
7495 if (I->isMoveAssignmentOperator()) {
7496 UserDeclaredMove = I;
7497 break;
7498 }
7499 }
7500 assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7500, __PRETTY_FUNCTION__))
;
7501 }
7502
7503 if (UserDeclaredMove) {
7504 Diag(UserDeclaredMove->getLocation(),
7505 diag::note_deleted_copy_user_declared_move)
7506 << (CSM == CXXCopyAssignment) << RD
7507 << UserDeclaredMove->isMoveAssignmentOperator();
7508 return true;
7509 }
7510 }
7511
7512 // Do access control from the special member function
7513 ContextRAII MethodContext(*this, MD);
7514
7515 // C++11 [class.dtor]p5:
7516 // -- for a virtual destructor, lookup of the non-array deallocation function
7517 // results in an ambiguity or in a function that is deleted or inaccessible
7518 if (CSM == CXXDestructor && MD->isVirtual()) {
7519 FunctionDecl *OperatorDelete = nullptr;
7520 DeclarationName Name =
7521 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7522 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7523 OperatorDelete, /*Diagnose*/false)) {
7524 if (Diagnose)
7525 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7526 return true;
7527 }
7528 }
7529
7530 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7531
7532 // Per DR1611, do not consider virtual bases of constructors of abstract
7533 // classes, since we are not going to construct them.
7534 // Per DR1658, do not consider virtual bases of destructors of abstract
7535 // classes either.
7536 // Per DR2180, for assignment operators we only assign (and thus only
7537 // consider) direct bases.
7538 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7539 : SMI.VisitPotentiallyConstructedBases))
7540 return true;
7541
7542 if (SMI.shouldDeleteForAllConstMembers())
7543 return true;
7544
7545 if (getLangOpts().CUDA) {
7546 // We should delete the special member in CUDA mode if target inference
7547 // failed.
7548 // For inherited constructors (non-null ICI), CSM may be passed so that MD
7549 // is treated as certain special member, which may not reflect what special
7550 // member MD really is. However inferCUDATargetForImplicitSpecialMember
7551 // expects CSM to match MD, therefore recalculate CSM.
7552 assert(ICI || CSM == getSpecialMember(MD))((ICI || CSM == getSpecialMember(MD)) ? static_cast<void>
(0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7552, __PRETTY_FUNCTION__))
;
7553 auto RealCSM = CSM;
7554 if (ICI)
7555 RealCSM = getSpecialMember(MD);
7556
7557 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7558 SMI.ConstArg, Diagnose);
7559 }
7560
7561 return false;
7562}
7563
7564/// Perform lookup for a special member of the specified kind, and determine
7565/// whether it is trivial. If the triviality can be determined without the
7566/// lookup, skip it. This is intended for use when determining whether a
7567/// special member of a containing object is trivial, and thus does not ever
7568/// perform overload resolution for default constructors.
7569///
7570/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7571/// member that was most likely to be intended to be trivial, if any.
7572///
7573/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7574/// determine whether the special member is trivial.
7575static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7576 Sema::CXXSpecialMember CSM, unsigned Quals,
7577 bool ConstRHS,
7578 Sema::TrivialABIHandling TAH,
7579 CXXMethodDecl **Selected) {
7580 if (Selected)
7581 *Selected = nullptr;
7582
7583 switch (CSM) {
7584 case Sema::CXXInvalid:
7585 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7585)
;
7586
7587 case Sema::CXXDefaultConstructor:
7588 // C++11 [class.ctor]p5:
7589 // A default constructor is trivial if:
7590 // - all the [direct subobjects] have trivial default constructors
7591 //
7592 // Note, no overload resolution is performed in this case.
7593 if (RD->hasTrivialDefaultConstructor())
7594 return true;
7595
7596 if (Selected) {
7597 // If there's a default constructor which could have been trivial, dig it
7598 // out. Otherwise, if there's any user-provided default constructor, point
7599 // to that as an example of why there's not a trivial one.
7600 CXXConstructorDecl *DefCtor = nullptr;
7601 if (RD->needsImplicitDefaultConstructor())
7602 S.DeclareImplicitDefaultConstructor(RD);
7603 for (auto *CI : RD->ctors()) {
7604 if (!CI->isDefaultConstructor())
7605 continue;
7606 DefCtor = CI;
7607 if (!DefCtor->isUserProvided())
7608 break;
7609 }
7610
7611 *Selected = DefCtor;
7612 }
7613
7614 return false;
7615
7616 case Sema::CXXDestructor:
7617 // C++11 [class.dtor]p5:
7618 // A destructor is trivial if:
7619 // - all the direct [subobjects] have trivial destructors
7620 if (RD->hasTrivialDestructor() ||
7621 (TAH == Sema::TAH_ConsiderTrivialABI &&
7622 RD->hasTrivialDestructorForCall()))
7623 return true;
7624
7625 if (Selected) {
7626 if (RD->needsImplicitDestructor())
7627 S.DeclareImplicitDestructor(RD);
7628 *Selected = RD->getDestructor();
7629 }
7630
7631 return false;
7632
7633 case Sema::CXXCopyConstructor:
7634 // C++11 [class.copy]p12:
7635 // A copy constructor is trivial if:
7636 // - the constructor selected to copy each direct [subobject] is trivial
7637 if (RD->hasTrivialCopyConstructor() ||
7638 (TAH == Sema::TAH_ConsiderTrivialABI &&
7639 RD->hasTrivialCopyConstructorForCall())) {
7640 if (Quals == Qualifiers::Const)
7641 // We must either select the trivial copy constructor or reach an
7642 // ambiguity; no need to actually perform overload resolution.
7643 return true;
7644 } else if (!Selected) {
7645 return false;
7646 }
7647 // In C++98, we are not supposed to perform overload resolution here, but we
7648 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7649 // cases like B as having a non-trivial copy constructor:
7650 // struct A { template<typename T> A(T&); };
7651 // struct B { mutable A a; };
7652 goto NeedOverloadResolution;
7653
7654 case Sema::CXXCopyAssignment:
7655 // C++11 [class.copy]p25:
7656 // A copy assignment operator is trivial if:
7657 // - the assignment operator selected to copy each direct [subobject] is
7658 // trivial
7659 if (RD->hasTrivialCopyAssignment()) {
7660 if (Quals == Qualifiers::Const)
7661 return true;
7662 } else if (!Selected) {
7663 return false;
7664 }
7665 // In C++98, we are not supposed to perform overload resolution here, but we
7666 // treat that as a language defect.
7667 goto NeedOverloadResolution;
7668
7669 case Sema::CXXMoveConstructor:
7670 case Sema::CXXMoveAssignment:
7671 NeedOverloadResolution:
7672 Sema::SpecialMemberOverloadResult SMOR =
7673 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7674
7675 // The standard doesn't describe how to behave if the lookup is ambiguous.
7676 // We treat it as not making the member non-trivial, just like the standard
7677 // mandates for the default constructor. This should rarely matter, because
7678 // the member will also be deleted.
7679 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7680 return true;
7681
7682 if (!SMOR.getMethod()) {
7683 assert(SMOR.getKind() ==((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7684, __PRETTY_FUNCTION__))
7684 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted
) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7684, __PRETTY_FUNCTION__))
;
7685 return false;
7686 }
7687
7688 // We deliberately don't check if we found a deleted special member. We're
7689 // not supposed to!
7690 if (Selected)
7691 *Selected = SMOR.getMethod();
7692
7693 if (TAH == Sema::TAH_ConsiderTrivialABI &&
7694 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7695 return SMOR.getMethod()->isTrivialForCall();
7696 return SMOR.getMethod()->isTrivial();
7697 }
7698
7699 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7699)
;
7700}
7701
7702static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7703 for (auto *CI : RD->ctors())
7704 if (!CI->isImplicit())
7705 return CI;
7706
7707 // Look for constructor templates.
7708 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7709 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7710 if (CXXConstructorDecl *CD =
7711 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7712 return CD;
7713 }
7714
7715 return nullptr;
7716}
7717
7718/// The kind of subobject we are checking for triviality. The values of this
7719/// enumeration are used in diagnostics.
7720enum TrivialSubobjectKind {
7721 /// The subobject is a base class.
7722 TSK_BaseClass,
7723 /// The subobject is a non-static data member.
7724 TSK_Field,
7725 /// The object is actually the complete object.
7726 TSK_CompleteObject
7727};
7728
7729/// Check whether the special member selected for a given type would be trivial.
7730static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7731 QualType SubType, bool ConstRHS,
7732 Sema::CXXSpecialMember CSM,
7733 TrivialSubobjectKind Kind,
7734 Sema::TrivialABIHandling TAH, bool Diagnose) {
7735 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7736 if (!SubRD)
7737 return true;
7738
7739 CXXMethodDecl *Selected;
7740 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7741 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7742 return true;
7743
7744 if (Diagnose) {
7745 if (ConstRHS)
7746 SubType.addConst();
7747
7748 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7749 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7750 << Kind << SubType.getUnqualifiedType();
7751 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7752 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7753 } else if (!Selected)
7754 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7755 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7756 else if (Selected->isUserProvided()) {
7757 if (Kind == TSK_CompleteObject)
7758 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7759 << Kind << SubType.getUnqualifiedType() << CSM;
7760 else {
7761 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7762 << Kind << SubType.getUnqualifiedType() << CSM;
7763 S.Diag(Selected->getLocation(), diag::note_declared_at);
7764 }
7765 } else {
7766 if (Kind != TSK_CompleteObject)
7767 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7768 << Kind << SubType.getUnqualifiedType() << CSM;
7769
7770 // Explain why the defaulted or deleted special member isn't trivial.
7771 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7772 Diagnose);
7773 }
7774 }
7775
7776 return false;
7777}
7778
7779/// Check whether the members of a class type allow a special member to be
7780/// trivial.
7781static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7782 Sema::CXXSpecialMember CSM,
7783 bool ConstArg,
7784 Sema::TrivialABIHandling TAH,
7785 bool Diagnose) {
7786 for (const auto *FI : RD->fields()) {
7787 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7788 continue;
7789
7790 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7791
7792 // Pretend anonymous struct or union members are members of this class.
7793 if (FI->isAnonymousStructOrUnion()) {
7794 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7795 CSM, ConstArg, TAH, Diagnose))
7796 return false;
7797 continue;
7798 }
7799
7800 // C++11 [class.ctor]p5:
7801 // A default constructor is trivial if [...]
7802 // -- no non-static data member of its class has a
7803 // brace-or-equal-initializer
7804 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7805 if (Diagnose)
7806 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7807 return false;
7808 }
7809
7810 // Objective C ARC 4.3.5:
7811 // [...] nontrivally ownership-qualified types are [...] not trivially
7812 // default constructible, copy constructible, move constructible, copy
7813 // assignable, move assignable, or destructible [...]
7814 if (FieldType.hasNonTrivialObjCLifetime()) {
7815 if (Diagnose)
7816 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7817 << RD << FieldType.getObjCLifetime();
7818 return false;
7819 }
7820
7821 bool ConstRHS = ConstArg && !FI->isMutable();
7822 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7823 CSM, TSK_Field, TAH, Diagnose))
7824 return false;
7825 }
7826
7827 return true;
7828}
7829
7830/// Diagnose why the specified class does not have a trivial special member of
7831/// the given kind.
7832void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7833 QualType Ty = Context.getRecordType(RD);
7834
7835 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7836 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7837 TSK_CompleteObject, TAH_IgnoreTrivialABI,
7838 /*Diagnose*/true);
7839}
7840
7841/// Determine whether a defaulted or deleted special member function is trivial,
7842/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7843/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7844bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7845 TrivialABIHandling TAH, bool Diagnose) {
7846 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")((!MD->isUserProvided() && CSM != CXXInvalid &&
"not special enough") ? static_cast<void> (0) : __assert_fail
("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7846, __PRETTY_FUNCTION__))
;
7847
7848 CXXRecordDecl *RD = MD->getParent();
7849
7850 bool ConstArg = false;
7851
7852 // C++11 [class.copy]p12, p25: [DR1593]
7853 // A [special member] is trivial if [...] its parameter-type-list is
7854 // equivalent to the parameter-type-list of an implicit declaration [...]
7855 switch (CSM) {
7856 case CXXDefaultConstructor:
7857 case CXXDestructor:
7858 // Trivial default constructors and destructors cannot have parameters.
7859 break;
7860
7861 case CXXCopyConstructor:
7862 case CXXCopyAssignment: {
7863 // Trivial copy operations always have const, non-volatile parameter types.
7864 ConstArg = true;
7865 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7866 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7867 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7868 if (Diagnose)
7869 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7870 << Param0->getSourceRange() << Param0->getType()
7871 << Context.getLValueReferenceType(
7872 Context.getRecordType(RD).withConst());
7873 return false;
7874 }
7875 break;
7876 }
7877
7878 case CXXMoveConstructor:
7879 case CXXMoveAssignment: {
7880 // Trivial move operations always have non-cv-qualified parameters.
7881 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7882 const RValueReferenceType *RT =
7883 Param0->getType()->getAs<RValueReferenceType>();
7884 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7885 if (Diagnose)
7886 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7887 << Param0->getSourceRange() << Param0->getType()
7888 << Context.getRValueReferenceType(Context.getRecordType(RD));
7889 return false;
7890 }
7891 break;
7892 }
7893
7894 case CXXInvalid:
7895 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7895)
;
7896 }
7897
7898 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7899 if (Diagnose)
7900 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7901 diag::note_nontrivial_default_arg)
7902 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7903 return false;
7904 }
7905 if (MD->isVariadic()) {
7906 if (Diagnose)
7907 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7908 return false;
7909 }
7910
7911 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7912 // A copy/move [constructor or assignment operator] is trivial if
7913 // -- the [member] selected to copy/move each direct base class subobject
7914 // is trivial
7915 //
7916 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7917 // A [default constructor or destructor] is trivial if
7918 // -- all the direct base classes have trivial [default constructors or
7919 // destructors]
7920 for (const auto &BI : RD->bases())
7921 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7922 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7923 return false;
7924
7925 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7926 // A copy/move [constructor or assignment operator] for a class X is
7927 // trivial if
7928 // -- for each non-static data member of X that is of class type (or array
7929 // thereof), the constructor selected to copy/move that member is
7930 // trivial
7931 //
7932 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7933 // A [default constructor or destructor] is trivial if
7934 // -- for all of the non-static data members of its class that are of class
7935 // type (or array thereof), each such class has a trivial [default
7936 // constructor or destructor]
7937 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7938 return false;
7939
7940 // C++11 [class.dtor]p5:
7941 // A destructor is trivial if [...]
7942 // -- the destructor is not virtual
7943 if (CSM == CXXDestructor && MD->isVirtual()) {
7944 if (Diagnose)
7945 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7946 return false;
7947 }
7948
7949 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7950 // A [special member] for class X is trivial if [...]
7951 // -- class X has no virtual functions and no virtual base classes
7952 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7953 if (!Diagnose)
7954 return false;
7955
7956 if (RD->getNumVBases()) {
7957 // Check for virtual bases. We already know that the corresponding
7958 // member in all bases is trivial, so vbases must all be direct.
7959 CXXBaseSpecifier &BS = *RD->vbases_begin();
7960 assert(BS.isVirtual())((BS.isVirtual()) ? static_cast<void> (0) : __assert_fail
("BS.isVirtual()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7960, __PRETTY_FUNCTION__))
;
7961 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7962 return false;
7963 }
7964
7965 // Must have a virtual method.
7966 for (const auto *MI : RD->methods()) {
7967 if (MI->isVirtual()) {
7968 SourceLocation MLoc = MI->getBeginLoc();
7969 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7970 return false;
7971 }
7972 }
7973
7974 llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 7974)
;
7975 }
7976
7977 // Looks like it's trivial!
7978 return true;
7979}
7980
7981namespace {
7982struct FindHiddenVirtualMethod {
7983 Sema *S;
7984 CXXMethodDecl *Method;
7985 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7986 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7987
7988private:
7989 /// Check whether any most overridden method from MD in Methods
7990 static bool CheckMostOverridenMethods(
7991 const CXXMethodDecl *MD,
7992 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7993 if (MD->size_overridden_methods() == 0)
7994 return Methods.count(MD->getCanonicalDecl());
7995 for (const CXXMethodDecl *O : MD->overridden_methods())
7996 if (CheckMostOverridenMethods(O, Methods))
7997 return true;
7998 return false;
7999 }
8000
8001public:
8002 /// Member lookup function that determines whether a given C++
8003 /// method overloads virtual methods in a base class without overriding any,
8004 /// to be used with CXXRecordDecl::lookupInBases().
8005 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8006 RecordDecl *BaseRecord =
8007 Specifier->getType()->getAs<RecordType>()->getDecl();
8008
8009 DeclarationName Name = Method->getDeclName();
8010 assert(Name.getNameKind() == DeclarationName::Identifier)((Name.getNameKind() == DeclarationName::Identifier) ? static_cast
<void> (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8010, __PRETTY_FUNCTION__))
;
8011
8012 bool foundSameNameMethod = false;
8013 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
8014 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8015 Path.Decls = Path.Decls.slice(1)) {
8016 NamedDecl *D = Path.Decls.front();
8017 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8018 MD = MD->getCanonicalDecl();
8019 foundSameNameMethod = true;
8020 // Interested only in hidden virtual methods.
8021 if (!MD->isVirtual())
8022 continue;
8023 // If the method we are checking overrides a method from its base
8024 // don't warn about the other overloaded methods. Clang deviates from
8025 // GCC by only diagnosing overloads of inherited virtual functions that
8026 // do not override any other virtual functions in the base. GCC's
8027 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
8028 // function from a base class. These cases may be better served by a
8029 // warning (not specific to virtual functions) on call sites when the
8030 // call would select a different function from the base class, were it
8031 // visible.
8032 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
8033 if (!S->IsOverload(Method, MD, false))
8034 return true;
8035 // Collect the overload only if its hidden.
8036 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
8037 overloadedMethods.push_back(MD);
8038 }
8039 }
8040
8041 if (foundSameNameMethod)
8042 OverloadedMethods.append(overloadedMethods.begin(),
8043 overloadedMethods.end());
8044 return foundSameNameMethod;
8045 }
8046};
8047} // end anonymous namespace
8048
8049/// Add the most overriden methods from MD to Methods
8050static void AddMostOverridenMethods(const CXXMethodDecl *MD,
8051 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
8052 if (MD->size_overridden_methods() == 0)
8053 Methods.insert(MD->getCanonicalDecl());
8054 else
8055 for (const CXXMethodDecl *O : MD->overridden_methods())
8056 AddMostOverridenMethods(O, Methods);
8057}
8058
8059/// Check if a method overloads virtual methods in a base class without
8060/// overriding any.
8061void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
8062 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8063 if (!MD->getDeclName().isIdentifier())
8064 return;
8065
8066 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
8067 /*bool RecordPaths=*/false,
8068 /*bool DetectVirtual=*/false);
8069 FindHiddenVirtualMethod FHVM;
8070 FHVM.Method = MD;
8071 FHVM.S = this;
8072
8073 // Keep the base methods that were overridden or introduced in the subclass
8074 // by 'using' in a set. A base method not in this set is hidden.
8075 CXXRecordDecl *DC = MD->getParent();
8076 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
8077 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
8078 NamedDecl *ND = *I;
8079 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
8080 ND = shad->getTargetDecl();
8081 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
8082 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
8083 }
8084
8085 if (DC->lookupInBases(FHVM, Paths))
8086 OverloadedMethods = FHVM.OverloadedMethods;
8087}
8088
8089void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
8090 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8091 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
8092 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
8093 PartialDiagnostic PD = PDiag(
8094 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
8095 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
8096 Diag(overloadedMD->getLocation(), PD);
8097 }
8098}
8099
8100/// Diagnose methods which overload virtual methods in a base class
8101/// without overriding any.
8102void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
8103 if (MD->isInvalidDecl())
8104 return;
8105
8106 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
8107 return;
8108
8109 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
8110 FindHiddenVirtualMethods(MD, OverloadedMethods);
8111 if (!OverloadedMethods.empty()) {
8112 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
8113 << MD << (OverloadedMethods.size() > 1);
8114
8115 NoteHiddenVirtualMethods(MD, OverloadedMethods);
8116 }
8117}
8118
8119void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
8120 auto PrintDiagAndRemoveAttr = [&]() {
8121 // No diagnostics if this is a template instantiation.
8122 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
8123 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
8124 diag::ext_cannot_use_trivial_abi) << &RD;
8125 RD.dropAttr<TrivialABIAttr>();
8126 };
8127
8128 // Ill-formed if the struct has virtual functions.
8129 if (RD.isPolymorphic()) {
8130 PrintDiagAndRemoveAttr();
8131 return;
8132 }
8133
8134 for (const auto &B : RD.bases()) {
8135 // Ill-formed if the base class is non-trivial for the purpose of calls or a
8136 // virtual base.
8137 if ((!B.getType()->isDependentType() &&
8138 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
8139 B.isVirtual()) {
8140 PrintDiagAndRemoveAttr();
8141 return;
8142 }
8143 }
8144
8145 for (const auto *FD : RD.fields()) {
8146 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
8147 // non-trivial for the purpose of calls.
8148 QualType FT = FD->getType();
8149 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
8150 PrintDiagAndRemoveAttr();
8151 return;
8152 }
8153
8154 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
8155 if (!RT->isDependentType() &&
8156 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
8157 PrintDiagAndRemoveAttr();
8158 return;
8159 }
8160 }
8161}
8162
8163void Sema::ActOnFinishCXXMemberSpecification(
8164 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
8165 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
8166 if (!TagDecl)
8167 return;
8168
8169 AdjustDeclIfTemplate(TagDecl);
8170
8171 for (const ParsedAttr &AL : AttrList) {
8172 if (AL.getKind() != ParsedAttr::AT_Visibility)
8173 continue;
8174 AL.setInvalid();
8175 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
8176 }
8177
8178 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
8179 // strict aliasing violation!
8180 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
8181 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
8182
8183 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
8184}
8185
8186/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
8187/// special functions, such as the default constructor, copy
8188/// constructor, or destructor, to the given C++ class (C++
8189/// [special]p1). This routine can only be executed just before the
8190/// definition of the class is complete.
8191void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
8192 if (ClassDecl->needsImplicitDefaultConstructor()) {
8193 ++getASTContext().NumImplicitDefaultConstructors;
8194
8195 if (ClassDecl->hasInheritedConstructor())
8196 DeclareImplicitDefaultConstructor(ClassDecl);
8197 }
8198
8199 if (ClassDecl->needsImplicitCopyConstructor()) {
8200 ++getASTContext().NumImplicitCopyConstructors;
8201
8202 // If the properties or semantics of the copy constructor couldn't be
8203 // determined while the class was being declared, force a declaration
8204 // of it now.
8205 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
8206 ClassDecl->hasInheritedConstructor())
8207 DeclareImplicitCopyConstructor(ClassDecl);
8208 // For the MS ABI we need to know whether the copy ctor is deleted. A
8209 // prerequisite for deleting the implicit copy ctor is that the class has a
8210 // move ctor or move assignment that is either user-declared or whose
8211 // semantics are inherited from a subobject. FIXME: We should provide a more
8212 // direct way for CodeGen to ask whether the constructor was deleted.
8213 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8214 (ClassDecl->hasUserDeclaredMoveConstructor() ||
8215 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8216 ClassDecl->hasUserDeclaredMoveAssignment() ||
8217 ClassDecl->needsOverloadResolutionForMoveAssignment()))
8218 DeclareImplicitCopyConstructor(ClassDecl);
8219 }
8220
8221 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8222 ++getASTContext().NumImplicitMoveConstructors;
8223
8224 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8225 ClassDecl->hasInheritedConstructor())
8226 DeclareImplicitMoveConstructor(ClassDecl);
8227 }
8228
8229 if (ClassDecl->needsImplicitCopyAssignment()) {
8230 ++getASTContext().NumImplicitCopyAssignmentOperators;
8231
8232 // If we have a dynamic class, then the copy assignment operator may be
8233 // virtual, so we have to declare it immediately. This ensures that, e.g.,
8234 // it shows up in the right place in the vtable and that we diagnose
8235 // problems with the implicit exception specification.
8236 if (ClassDecl->isDynamicClass() ||
8237 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8238 ClassDecl->hasInheritedAssignment())
8239 DeclareImplicitCopyAssignment(ClassDecl);
8240 }
8241
8242 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8243 ++getASTContext().NumImplicitMoveAssignmentOperators;
8244
8245 // Likewise for the move assignment operator.
8246 if (ClassDecl->isDynamicClass() ||
8247 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8248 ClassDecl->hasInheritedAssignment())
8249 DeclareImplicitMoveAssignment(ClassDecl);
8250 }
8251
8252 if (ClassDecl->needsImplicitDestructor()) {
8253 ++getASTContext().NumImplicitDestructors;
8254
8255 // If we have a dynamic class, then the destructor may be virtual, so we
8256 // have to declare the destructor immediately. This ensures that, e.g., it
8257 // shows up in the right place in the vtable and that we diagnose problems
8258 // with the implicit exception specification.
8259 if (ClassDecl->isDynamicClass() ||
8260 ClassDecl->needsOverloadResolutionForDestructor())
8261 DeclareImplicitDestructor(ClassDecl);
8262 }
8263}
8264
8265unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8266 if (!D)
8267 return 0;
8268
8269 // The order of template parameters is not important here. All names
8270 // get added to the same scope.
8271 SmallVector<TemplateParameterList *, 4> ParameterLists;
8272
8273 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8274 D = TD->getTemplatedDecl();
8275
8276 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8277 ParameterLists.push_back(PSD->getTemplateParameters());
8278
8279 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8280 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8281 ParameterLists.push_back(DD->getTemplateParameterList(i));
8282
8283 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8284 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8285 ParameterLists.push_back(FTD->getTemplateParameters());
8286 }
8287 }
8288
8289 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8290 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8291 ParameterLists.push_back(TD->getTemplateParameterList(i));
8292
8293 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8294 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8295 ParameterLists.push_back(CTD->getTemplateParameters());
8296 }
8297 }
8298
8299 unsigned Count = 0;
8300 for (TemplateParameterList *Params : ParameterLists) {
8301 if (Params->size() > 0)
8302 // Ignore explicit specializations; they don't contribute to the template
8303 // depth.
8304 ++Count;
8305 for (NamedDecl *Param : *Params) {
8306 if (Param->getDeclName()) {
8307 S->AddDecl(Param);
8308 IdResolver.AddDecl(Param);
8309 }
8310 }
8311 }
8312
8313 return Count;
8314}
8315
8316void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8317 if (!RecordD) return;
8318 AdjustDeclIfTemplate(RecordD);
8319 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8320 PushDeclContext(S, Record);
8321}
8322
8323void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8324 if (!RecordD) return;
8325 PopDeclContext();
8326}
8327
8328/// This is used to implement the constant expression evaluation part of the
8329/// attribute enable_if extension. There is nothing in standard C++ which would
8330/// require reentering parameters.
8331void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8332 if (!Param)
8333 return;
8334
8335 S->AddDecl(Param);
8336 if (Param->getDeclName())
8337 IdResolver.AddDecl(Param);
8338}
8339
8340/// ActOnStartDelayedCXXMethodDeclaration - We have completed
8341/// parsing a top-level (non-nested) C++ class, and we are now
8342/// parsing those parts of the given Method declaration that could
8343/// not be parsed earlier (C++ [class.mem]p2), such as default
8344/// arguments. This action should enter the scope of the given
8345/// Method declaration as if we had just parsed the qualified method
8346/// name. However, it should not bring the parameters into scope;
8347/// that will be performed by ActOnDelayedCXXMethodParameter.
8348void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8349}
8350
8351/// ActOnDelayedCXXMethodParameter - We've already started a delayed
8352/// C++ method declaration. We're (re-)introducing the given
8353/// function parameter into scope for use in parsing later parts of
8354/// the method declaration. For example, we could see an
8355/// ActOnParamDefaultArgument event for this parameter.
8356void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8357 if (!ParamD)
8358 return;
8359
8360 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8361
8362 // If this parameter has an unparsed default argument, clear it out
8363 // to make way for the parsed default argument.
8364 if (Param->hasUnparsedDefaultArg())
8365 Param->setDefaultArg(nullptr);
8366
8367 S->AddDecl(Param);
8368 if (Param->getDeclName())
8369 IdResolver.AddDecl(Param);
8370}
8371
8372/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8373/// processing the delayed method declaration for Method. The method
8374/// declaration is now considered finished. There may be a separate
8375/// ActOnStartOfFunctionDef action later (not necessarily
8376/// immediately!) for this method, if it was also defined inside the
8377/// class body.
8378void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8379 if (!MethodD)
8380 return;
8381
8382 AdjustDeclIfTemplate(MethodD);
8383
8384 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8385
8386 // Now that we have our default arguments, check the constructor
8387 // again. It could produce additional diagnostics or affect whether
8388 // the class has implicitly-declared destructors, among other
8389 // things.
8390 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8391 CheckConstructor(Constructor);
8392
8393 // Check the default arguments, which we may have added.
8394 if (!Method->isInvalidDecl())
8395 CheckCXXDefaultArguments(Method);
8396}
8397
8398// Emit the given diagnostic for each non-address-space qualifier.
8399// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
8400static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
8401 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8402 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8403 bool DiagOccured = false;
8404 FTI.MethodQualifiers->forEachQualifier(
8405 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
8406 SourceLocation SL) {
8407 // This diagnostic should be emitted on any qualifier except an addr
8408 // space qualifier. However, forEachQualifier currently doesn't visit
8409 // addr space qualifiers, so there's no way to write this condition
8410 // right now; we just diagnose on everything.
8411 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
8412 DiagOccured = true;
8413 });
8414 if (DiagOccured)
8415 D.setInvalidType();
8416 }
8417}
8418
8419/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8420/// the well-formedness of the constructor declarator @p D with type @p
8421/// R. If there are any errors in the declarator, this routine will
8422/// emit diagnostics and set the invalid bit to true. In any case, the type
8423/// will be updated to reflect a well-formed type for the constructor and
8424/// returned.
8425QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8426 StorageClass &SC) {
8427 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8428
8429 // C++ [class.ctor]p3:
8430 // A constructor shall not be virtual (10.3) or static (9.4). A
8431 // constructor can be invoked for a const, volatile or const
8432 // volatile object. A constructor shall not be declared const,
8433 // volatile, or const volatile (9.3.2).
8434 if (isVirtual) {
8435 if (!D.isInvalidType())
8436 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8437 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8438 << SourceRange(D.getIdentifierLoc());
8439 D.setInvalidType();
8440 }
8441 if (SC == SC_Static) {
8442 if (!D.isInvalidType())
8443 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8444 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8445 << SourceRange(D.getIdentifierLoc());
8446 D.setInvalidType();
8447 SC = SC_None;
8448 }
8449
8450 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8451 diagnoseIgnoredQualifiers(
8452 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8453 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8454 D.getDeclSpec().getRestrictSpecLoc(),
8455 D.getDeclSpec().getAtomicSpecLoc());
8456 D.setInvalidType();
8457 }
8458
8459 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
8460
8461 // C++0x [class.ctor]p4:
8462 // A constructor shall not be declared with a ref-qualifier.
8463 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8464 if (FTI.hasRefQualifier()) {
8465 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8466 << FTI.RefQualifierIsLValueRef
8467 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8468 D.setInvalidType();
8469 }
8470
8471 // Rebuild the function type "R" without any type qualifiers (in
8472 // case any of the errors above fired) and with "void" as the
8473 // return type, since constructors don't have return types.
8474 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8475 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8476 return R;
8477
8478 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8479 EPI.TypeQuals = Qualifiers();
8480 EPI.RefQualifier = RQ_None;
8481
8482 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8483}
8484
8485/// CheckConstructor - Checks a fully-formed constructor for
8486/// well-formedness, issuing any diagnostics required. Returns true if
8487/// the constructor declarator is invalid.
8488void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8489 CXXRecordDecl *ClassDecl
8490 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8491 if (!ClassDecl)
8492 return Constructor->setInvalidDecl();
8493
8494 // C++ [class.copy]p3:
8495 // A declaration of a constructor for a class X is ill-formed if
8496 // its first parameter is of type (optionally cv-qualified) X and
8497 // either there are no other parameters or else all other
8498 // parameters have default arguments.
8499 if (!Constructor->isInvalidDecl() &&
8500 ((Constructor->getNumParams() == 1) ||
8501 (Constructor->getNumParams() > 1 &&
8502 Constructor->getParamDecl(1)->hasDefaultArg())) &&
8503 Constructor->getTemplateSpecializationKind()
8504 != TSK_ImplicitInstantiation) {
8505 QualType ParamType = Constructor->getParamDecl(0)->getType();
8506 QualType ClassTy = Context.getTagDeclType(ClassDecl);
8507 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8508 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8509 const char *ConstRef
8510 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8511 : " const &";
8512 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8513 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8514
8515 // FIXME: Rather that making the constructor invalid, we should endeavor
8516 // to fix the type.
8517 Constructor->setInvalidDecl();
8518 }
8519 }
8520}
8521
8522/// CheckDestructor - Checks a fully-formed destructor definition for
8523/// well-formedness, issuing any diagnostics required. Returns true
8524/// on error.
8525bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8526 CXXRecordDecl *RD = Destructor->getParent();
8527
8528 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8529 SourceLocation Loc;
8530
8531 if (!Destructor->isImplicit())
8532 Loc = Destructor->getLocation();
8533 else
8534 Loc = RD->getLocation();
8535
8536 // If we have a virtual destructor, look up the deallocation function
8537 if (FunctionDecl *OperatorDelete =
8538 FindDeallocationFunctionForDestructor(Loc, RD)) {
8539 Expr *ThisArg = nullptr;
8540
8541 // If the notional 'delete this' expression requires a non-trivial
8542 // conversion from 'this' to the type of a destroying operator delete's
8543 // first parameter, perform that conversion now.
8544 if (OperatorDelete->isDestroyingOperatorDelete()) {
8545 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8546 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8547 // C++ [class.dtor]p13:
8548 // ... as if for the expression 'delete this' appearing in a
8549 // non-virtual destructor of the destructor's class.
8550 ContextRAII SwitchContext(*this, Destructor);
8551 ExprResult This =
8552 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8553 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")((!This.isInvalid() && "couldn't form 'this' expr in dtor?"
) ? static_cast<void> (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8553, __PRETTY_FUNCTION__))
;
8554 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8555 if (This.isInvalid()) {
8556 // FIXME: Register this as a context note so that it comes out
8557 // in the right order.
8558 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8559 return true;
8560 }
8561 ThisArg = This.get();
8562 }
8563 }
8564
8565 DiagnoseUseOfDecl(OperatorDelete, Loc);
8566 MarkFunctionReferenced(Loc, OperatorDelete);
8567 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8568 }
8569 }
8570
8571 return false;
8572}
8573
8574/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8575/// the well-formednes of the destructor declarator @p D with type @p
8576/// R. If there are any errors in the declarator, this routine will
8577/// emit diagnostics and set the declarator to invalid. Even if this happens,
8578/// will be updated to reflect a well-formed type for the destructor and
8579/// returned.
8580QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8581 StorageClass& SC) {
8582 // C++ [class.dtor]p1:
8583 // [...] A typedef-name that names a class is a class-name
8584 // (7.1.3); however, a typedef-name that names a class shall not
8585 // be used as the identifier in the declarator for a destructor
8586 // declaration.
8587 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8588 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8589 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8590 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8591 else if (const TemplateSpecializationType *TST =
8592 DeclaratorType->getAs<TemplateSpecializationType>())
8593 if (TST->isTypeAlias())
8594 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8595 << DeclaratorType << 1;
8596
8597 // C++ [class.dtor]p2:
8598 // A destructor is used to destroy objects of its class type. A
8599 // destructor takes no parameters, and no return type can be
8600 // specified for it (not even void). The address of a destructor
8601 // shall not be taken. A destructor shall not be static. A
8602 // destructor can be invoked for a const, volatile or const
8603 // volatile object. A destructor shall not be declared const,
8604 // volatile or const volatile (9.3.2).
8605 if (SC == SC_Static) {
8606 if (!D.isInvalidType())
8607 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8608 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8609 << SourceRange(D.getIdentifierLoc())
8610 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8611
8612 SC = SC_None;
8613 }
8614 if (!D.isInvalidType()) {
8615 // Destructors don't have return types, but the parser will
8616 // happily parse something like:
8617 //
8618 // class X {
8619 // float ~X();
8620 // };
8621 //
8622 // The return type will be eliminated later.
8623 if (D.getDeclSpec().hasTypeSpecifier())
8624 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8625 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8626 << SourceRange(D.getIdentifierLoc());
8627 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8628 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8629 SourceLocation(),
8630 D.getDeclSpec().getConstSpecLoc(),
8631 D.getDeclSpec().getVolatileSpecLoc(),
8632 D.getDeclSpec().getRestrictSpecLoc(),
8633 D.getDeclSpec().getAtomicSpecLoc());
8634 D.setInvalidType();
8635 }
8636 }
8637
8638 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
8639
8640 // C++0x [class.dtor]p2:
8641 // A destructor shall not be declared with a ref-qualifier.
8642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8643 if (FTI.hasRefQualifier()) {
8644 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8645 << FTI.RefQualifierIsLValueRef
8646 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8647 D.setInvalidType();
8648 }
8649
8650 // Make sure we don't have any parameters.
8651 if (FTIHasNonVoidParameters(FTI)) {
8652 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8653
8654 // Delete the parameters.
8655 FTI.freeParams();
8656 D.setInvalidType();
8657 }
8658
8659 // Make sure the destructor isn't variadic.
8660 if (FTI.isVariadic) {
8661 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8662 D.setInvalidType();
8663 }
8664
8665 // Rebuild the function type "R" without any type qualifiers or
8666 // parameters (in case any of the errors above fired) and with
8667 // "void" as the return type, since destructors don't have return
8668 // types.
8669 if (!D.isInvalidType())
8670 return R;
8671
8672 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8673 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8674 EPI.Variadic = false;
8675 EPI.TypeQuals = Qualifiers();
8676 EPI.RefQualifier = RQ_None;
8677 return Context.getFunctionType(Context.VoidTy, None, EPI);
8678}
8679
8680static void extendLeft(SourceRange &R, SourceRange Before) {
8681 if (Before.isInvalid())
8682 return;
8683 R.setBegin(Before.getBegin());
8684 if (R.getEnd().isInvalid())
8685 R.setEnd(Before.getEnd());
8686}
8687
8688static void extendRight(SourceRange &R, SourceRange After) {
8689 if (After.isInvalid())
8690 return;
8691 if (R.getBegin().isInvalid())
8692 R.setBegin(After.getBegin());
8693 R.setEnd(After.getEnd());
8694}
8695
8696/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8697/// well-formednes of the conversion function declarator @p D with
8698/// type @p R. If there are any errors in the declarator, this routine
8699/// will emit diagnostics and return true. Otherwise, it will return
8700/// false. Either way, the type @p R will be updated to reflect a
8701/// well-formed type for the conversion operator.
8702void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8703 StorageClass& SC) {
8704 // C++ [class.conv.fct]p1:
8705 // Neither parameter types nor return type can be specified. The
8706 // type of a conversion function (8.3.5) is "function taking no
8707 // parameter returning conversion-type-id."
8708 if (SC == SC_Static) {
8709 if (!D.isInvalidType())
8710 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8711 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8712 << D.getName().getSourceRange();
8713 D.setInvalidType();
8714 SC = SC_None;
8715 }
8716
8717 TypeSourceInfo *ConvTSI = nullptr;
8718 QualType ConvType =
8719 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8720
8721 const DeclSpec &DS = D.getDeclSpec();
8722 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8723 // Conversion functions don't have return types, but the parser will
8724 // happily parse something like:
8725 //
8726 // class X {
8727 // float operator bool();
8728 // };
8729 //
8730 // The return type will be changed later anyway.
8731 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8732 << SourceRange(DS.getTypeSpecTypeLoc())
8733 << SourceRange(D.getIdentifierLoc());
8734 D.setInvalidType();
8735 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8736 // It's also plausible that the user writes type qualifiers in the wrong
8737 // place, such as:
8738 // struct S { const operator int(); };
8739 // FIXME: we could provide a fixit to move the qualifiers onto the
8740 // conversion type.
8741 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8742 << SourceRange(D.getIdentifierLoc()) << 0;
8743 D.setInvalidType();
8744 }
8745
8746 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8747
8748 // Make sure we don't have any parameters.
8749 if (Proto->getNumParams() > 0) {
8750 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8751
8752 // Delete the parameters.
8753 D.getFunctionTypeInfo().freeParams();
8754 D.setInvalidType();
8755 } else if (Proto->isVariadic()) {
8756 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8757 D.setInvalidType();
8758 }
8759
8760 // Diagnose "&operator bool()" and other such nonsense. This
8761 // is actually a gcc extension which we don't support.
8762 if (Proto->getReturnType() != ConvType) {
8763 bool NeedsTypedef = false;
8764 SourceRange Before, After;
8765
8766 // Walk the chunks and extract information on them for our diagnostic.
8767 bool PastFunctionChunk = false;
8768 for (auto &Chunk : D.type_objects()) {
8769 switch (Chunk.Kind) {
8770 case DeclaratorChunk::Function:
8771 if (!PastFunctionChunk) {
8772 if (Chunk.Fun.HasTrailingReturnType) {
8773 TypeSourceInfo *TRT = nullptr;
8774 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8775 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8776 }
8777 PastFunctionChunk = true;
8778 break;
8779 }
8780 LLVM_FALLTHROUGH[[gnu::fallthrough]];
8781 case DeclaratorChunk::Array:
8782 NeedsTypedef = true;
8783 extendRight(After, Chunk.getSourceRange());
8784 break;
8785
8786 case DeclaratorChunk::Pointer:
8787 case DeclaratorChunk::BlockPointer:
8788 case DeclaratorChunk::Reference:
8789 case DeclaratorChunk::MemberPointer:
8790 case DeclaratorChunk::Pipe:
8791 extendLeft(Before, Chunk.getSourceRange());
8792 break;
8793
8794 case DeclaratorChunk::Paren:
8795 extendLeft(Before, Chunk.Loc);
8796 extendRight(After, Chunk.EndLoc);
8797 break;
8798 }
8799 }
8800
8801 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8802 After.isValid() ? After.getBegin() :
8803 D.getIdentifierLoc();
8804 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8805 DB << Before << After;
8806
8807 if (!NeedsTypedef) {
8808 DB << /*don't need a typedef*/0;
8809
8810 // If we can provide a correct fix-it hint, do so.
8811 if (After.isInvalid() && ConvTSI) {
8812 SourceLocation InsertLoc =
8813 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8814 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8815 << FixItHint::CreateInsertionFromRange(
8816 InsertLoc, CharSourceRange::getTokenRange(Before))
8817 << FixItHint::CreateRemoval(Before);
8818 }
8819 } else if (!Proto->getReturnType()->isDependentType()) {
8820 DB << /*typedef*/1 << Proto->getReturnType();
8821 } else if (getLangOpts().CPlusPlus11) {
8822 DB << /*alias template*/2 << Proto->getReturnType();
8823 } else {
8824 DB << /*might not be fixable*/3;
8825 }
8826
8827 // Recover by incorporating the other type chunks into the result type.
8828 // Note, this does *not* change the name of the function. This is compatible
8829 // with the GCC extension:
8830 // struct S { &operator int(); } s;
8831 // int &r = s.operator int(); // ok in GCC
8832 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8833 ConvType = Proto->getReturnType();
8834 }
8835
8836 // C++ [class.conv.fct]p4:
8837 // The conversion-type-id shall not represent a function type nor
8838 // an array type.
8839 if (ConvType->isArrayType()) {
8840 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8841 ConvType = Context.getPointerType(ConvType);
8842 D.setInvalidType();
8843 } else if (ConvType->isFunctionType()) {
8844 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8845 ConvType = Context.getPointerType(ConvType);
8846 D.setInvalidType();
8847 }
8848
8849 // Rebuild the function type "R" without any parameters (in case any
8850 // of the errors above fired) and with the conversion type as the
8851 // return type.
8852 if (D.isInvalidType())
8853 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8854
8855 // C++0x explicit conversion operators.
8856 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8857 Diag(DS.getExplicitSpecLoc(),
8858 getLangOpts().CPlusPlus11
8859 ? diag::warn_cxx98_compat_explicit_conversion_functions
8860 : diag::ext_explicit_conversion_functions)
8861 << SourceRange(DS.getExplicitSpecRange());
8862}
8863
8864/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8865/// the declaration of the given C++ conversion function. This routine
8866/// is responsible for recording the conversion function in the C++
8867/// class, if possible.
8868Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8869 assert(Conversion && "Expected to receive a conversion function declaration")((Conversion && "Expected to receive a conversion function declaration"
) ? static_cast<void> (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8869, __PRETTY_FUNCTION__))
;
8870
8871 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8872
8873 // Make sure we aren't redeclaring the conversion function.
8874 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8875
8876 // C++ [class.conv.fct]p1:
8877 // [...] A conversion function is never used to convert a
8878 // (possibly cv-qualified) object to the (possibly cv-qualified)
8879 // same object type (or a reference to it), to a (possibly
8880 // cv-qualified) base class of that type (or a reference to it),
8881 // or to (possibly cv-qualified) void.
8882 // FIXME: Suppress this warning if the conversion function ends up being a
8883 // virtual function that overrides a virtual function in a base class.
8884 QualType ClassType
8885 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8886 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8887 ConvType = ConvTypeRef->getPointeeType();
8888 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8889 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8890 /* Suppress diagnostics for instantiations. */;
8891 else if (ConvType->isRecordType()) {
8892 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8893 if (ConvType == ClassType)
8894 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8895 << ClassType;
8896 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8897 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8898 << ClassType << ConvType;
8899 } else if (ConvType->isVoidType()) {
8900 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8901 << ClassType << ConvType;
8902 }
8903
8904 if (FunctionTemplateDecl *ConversionTemplate
8905 = Conversion->getDescribedFunctionTemplate())
8906 return ConversionTemplate;
8907
8908 return Conversion;
8909}
8910
8911namespace {
8912/// Utility class to accumulate and print a diagnostic listing the invalid
8913/// specifier(s) on a declaration.
8914struct BadSpecifierDiagnoser {
8915 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8916 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8917 ~BadSpecifierDiagnoser() {
8918 Diagnostic << Specifiers;
8919 }
8920
8921 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8922 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8923 }
8924 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8925 return check(SpecLoc,
8926 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8927 }
8928 void check(SourceLocation SpecLoc, const char *Spec) {
8929 if (SpecLoc.isInvalid()) return;
8930 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8931 if (!Specifiers.empty()) Specifiers += " ";
8932 Specifiers += Spec;
8933 }
8934
8935 Sema &S;
8936 Sema::SemaDiagnosticBuilder Diagnostic;
8937 std::string Specifiers;
8938};
8939}
8940
8941/// Check the validity of a declarator that we parsed for a deduction-guide.
8942/// These aren't actually declarators in the grammar, so we need to check that
8943/// the user didn't specify any pieces that are not part of the deduction-guide
8944/// grammar.
8945void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8946 StorageClass &SC) {
8947 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8948 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8949 assert(GuidedTemplateDecl && "missing template decl for deduction guide")((GuidedTemplateDecl && "missing template decl for deduction guide"
) ? static_cast<void> (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 8949, __PRETTY_FUNCTION__))
;
8950
8951 // C++ [temp.deduct.guide]p3:
8952 // A deduction-gide shall be declared in the same scope as the
8953 // corresponding class template.
8954 if (!CurContext->getRedeclContext()->Equals(
8955 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8956 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8957 << GuidedTemplateDecl;
8958 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8959 }
8960
8961 auto &DS = D.getMutableDeclSpec();
8962 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8963 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8964 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8965 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8966 BadSpecifierDiagnoser Diagnoser(
8967 *this, D.getIdentifierLoc(),
8968 diag::err_deduction_guide_invalid_specifier);
8969
8970 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8971 DS.ClearStorageClassSpecs();
8972 SC = SC_None;
8973
8974 // 'explicit' is permitted.
8975 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8976 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8977 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8978 DS.ClearConstexprSpec();
8979
8980 Diagnoser.check(DS.getConstSpecLoc(), "const");
8981 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8982 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8983 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8984 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8985 DS.ClearTypeQualifiers();
8986
8987 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8988 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8989 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8990 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8991 DS.ClearTypeSpecType();
8992 }
8993
8994 if (D.isInvalidType())
8995 return;
8996
8997 // Check the declarator is simple enough.
8998 bool FoundFunction = false;
8999 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
9000 if (Chunk.Kind == DeclaratorChunk::Paren)
9001 continue;
9002 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
9003 Diag(D.getDeclSpec().getBeginLoc(),
9004 diag::err_deduction_guide_with_complex_decl)
9005 << D.getSourceRange();
9006 break;
9007 }
9008 if (!Chunk.Fun.hasTrailingReturnType()) {
9009 Diag(D.getName().getBeginLoc(),
9010 diag::err_deduction_guide_no_trailing_return_type);
9011 break;
9012 }
9013
9014 // Check that the return type is written as a specialization of
9015 // the template specified as the deduction-guide's name.
9016 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
9017 TypeSourceInfo *TSI = nullptr;
9018 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
9019 assert(TSI && "deduction guide has valid type but invalid return type?")((TSI && "deduction guide has valid type but invalid return type?"
) ? static_cast<void> (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9019, __PRETTY_FUNCTION__))
;
9020 bool AcceptableReturnType = false;
9021 bool MightInstantiateToSpecialization = false;
9022 if (auto RetTST =
9023 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
9024 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
9025 bool TemplateMatches =
9026 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
9027 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
9028 AcceptableReturnType = true;
9029 else {
9030 // This could still instantiate to the right type, unless we know it
9031 // names the wrong class template.
9032 auto *TD = SpecifiedName.getAsTemplateDecl();
9033 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
9034 !TemplateMatches);
9035 }
9036 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
9037 MightInstantiateToSpecialization = true;
9038 }
9039
9040 if (!AcceptableReturnType) {
9041 Diag(TSI->getTypeLoc().getBeginLoc(),
9042 diag::err_deduction_guide_bad_trailing_return_type)
9043 << GuidedTemplate << TSI->getType()
9044 << MightInstantiateToSpecialization
9045 << TSI->getTypeLoc().getSourceRange();
9046 }
9047
9048 // Keep going to check that we don't have any inner declarator pieces (we
9049 // could still have a function returning a pointer to a function).
9050 FoundFunction = true;
9051 }
9052
9053 if (D.isFunctionDefinition())
9054 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
9055}
9056
9057//===----------------------------------------------------------------------===//
9058// Namespace Handling
9059//===----------------------------------------------------------------------===//
9060
9061/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
9062/// reopened.
9063static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
9064 SourceLocation Loc,
9065 IdentifierInfo *II, bool *IsInline,
9066 NamespaceDecl *PrevNS) {
9067 assert(*IsInline != PrevNS->isInline())((*IsInline != PrevNS->isInline()) ? static_cast<void>
(0) : __assert_fail ("*IsInline != PrevNS->isInline()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9067, __PRETTY_FUNCTION__))
;
9068
9069 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
9070 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
9071 // inline namespaces, with the intention of bringing names into namespace std.
9072 //
9073 // We support this just well enough to get that case working; this is not
9074 // sufficient to support reopening namespaces as inline in general.
9075 if (*IsInline && II && II->getName().startswith("__atomic") &&
9076 S.getSourceManager().isInSystemHeader(Loc)) {
9077 // Mark all prior declarations of the namespace as inline.
9078 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
9079 NS = NS->getPreviousDecl())
9080 NS->setInline(*IsInline);
9081 // Patch up the lookup table for the containing namespace. This isn't really
9082 // correct, but it's good enough for this particular case.
9083 for (auto *I : PrevNS->decls())
9084 if (auto *ND = dyn_cast<NamedDecl>(I))
9085 PrevNS->getParent()->makeDeclVisibleInContext(ND);
9086 return;
9087 }
9088
9089 if (PrevNS->isInline())
9090 // The user probably just forgot the 'inline', so suggest that it
9091 // be added back.
9092 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
9093 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
9094 else
9095 S.Diag(Loc, diag::err_inline_namespace_mismatch);
9096
9097 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
9098 *IsInline = PrevNS->isInline();
9099}
9100
9101/// ActOnStartNamespaceDef - This is called at the start of a namespace
9102/// definition.
9103Decl *Sema::ActOnStartNamespaceDef(
9104 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
9105 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
9106 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
9107 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
9108 // For anonymous namespace, take the location of the left brace.
9109 SourceLocation Loc = II ? IdentLoc : LBrace;
9110 bool IsInline = InlineLoc.isValid();
9111 bool IsInvalid = false;
9112 bool IsStd = false;
9113 bool AddToKnown = false;
9114 Scope *DeclRegionScope = NamespcScope->getParent();
9115
9116 NamespaceDecl *PrevNS = nullptr;
9117 if (II) {
9118 // C++ [namespace.def]p2:
9119 // The identifier in an original-namespace-definition shall not
9120 // have been previously defined in the declarative region in
9121 // which the original-namespace-definition appears. The
9122 // identifier in an original-namespace-definition is the name of
9123 // the namespace. Subsequently in that declarative region, it is
9124 // treated as an original-namespace-name.
9125 //
9126 // Since namespace names are unique in their scope, and we don't
9127 // look through using directives, just look for any ordinary names
9128 // as if by qualified name lookup.
9129 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
9130 ForExternalRedeclaration);
9131 LookupQualifiedName(R, CurContext->getRedeclContext());
9132 NamedDecl *PrevDecl =
9133 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
9134 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
9135
9136 if (PrevNS) {
9137 // This is an extended namespace definition.
9138 if (IsInline != PrevNS->isInline())
9139 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
9140 &IsInline, PrevNS);
9141 } else if (PrevDecl) {
9142 // This is an invalid name redefinition.
9143 Diag(Loc, diag::err_redefinition_different_kind)
9144 << II;
9145 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9146 IsInvalid = true;
9147 // Continue on to push Namespc as current DeclContext and return it.
9148 } else if (II->isStr("std") &&
9149 CurContext->getRedeclContext()->isTranslationUnit()) {
9150 // This is the first "real" definition of the namespace "std", so update
9151 // our cache of the "std" namespace to point at this definition.
9152 PrevNS = getStdNamespace();
9153 IsStd = true;
9154 AddToKnown = !IsInline;
9155 } else {
9156 // We've seen this namespace for the first time.
9157 AddToKnown = !IsInline;
9158 }
9159 } else {
9160 // Anonymous namespaces.
9161
9162 // Determine whether the parent already has an anonymous namespace.
9163 DeclContext *Parent = CurContext->getRedeclContext();
9164 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9165 PrevNS = TU->getAnonymousNamespace();
9166 } else {
9167 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
9168 PrevNS = ND->getAnonymousNamespace();
9169 }
9170
9171 if (PrevNS && IsInline != PrevNS->isInline())
9172 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
9173 &IsInline, PrevNS);
9174 }
9175
9176 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
9177 StartLoc, Loc, II, PrevNS);
9178 if (IsInvalid)
9179 Namespc->setInvalidDecl();
9180
9181 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
9182 AddPragmaAttributes(DeclRegionScope, Namespc);
9183
9184 // FIXME: Should we be merging attributes?
9185 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
9186 PushNamespaceVisibilityAttr(Attr, Loc);
9187
9188 if (IsStd)
9189 StdNamespace = Namespc;
9190 if (AddToKnown)
9191 KnownNamespaces[Namespc] = false;
9192
9193 if (II) {
9194 PushOnScopeChains(Namespc, DeclRegionScope);
9195 } else {
9196 // Link the anonymous namespace into its parent.
9197 DeclContext *Parent = CurContext->getRedeclContext();
9198 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9199 TU->setAnonymousNamespace(Namespc);
9200 } else {
9201 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
9202 }
9203
9204 CurContext->addDecl(Namespc);
9205
9206 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
9207 // behaves as if it were replaced by
9208 // namespace unique { /* empty body */ }
9209 // using namespace unique;
9210 // namespace unique { namespace-body }
9211 // where all occurrences of 'unique' in a translation unit are
9212 // replaced by the same identifier and this identifier differs
9213 // from all other identifiers in the entire program.
9214
9215 // We just create the namespace with an empty name and then add an
9216 // implicit using declaration, just like the standard suggests.
9217 //
9218 // CodeGen enforces the "universally unique" aspect by giving all
9219 // declarations semantically contained within an anonymous
9220 // namespace internal linkage.
9221
9222 if (!PrevNS) {
9223 UD = UsingDirectiveDecl::Create(Context, Parent,
9224 /* 'using' */ LBrace,
9225 /* 'namespace' */ SourceLocation(),
9226 /* qualifier */ NestedNameSpecifierLoc(),
9227 /* identifier */ SourceLocation(),
9228 Namespc,
9229 /* Ancestor */ Parent);
9230 UD->setImplicit();
9231 Parent->addDecl(UD);
9232 }
9233 }
9234
9235 ActOnDocumentableDecl(Namespc);
9236
9237 // Although we could have an invalid decl (i.e. the namespace name is a
9238 // redefinition), push it as current DeclContext and try to continue parsing.
9239 // FIXME: We should be able to push Namespc here, so that the each DeclContext
9240 // for the namespace has the declarations that showed up in that particular
9241 // namespace definition.
9242 PushDeclContext(NamespcScope, Namespc);
9243 return Namespc;
9244}
9245
9246/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9247/// is a namespace alias, returns the namespace it points to.
9248static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9249 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9250 return AD->getNamespace();
9251 return dyn_cast_or_null<NamespaceDecl>(D);
9252}
9253
9254/// ActOnFinishNamespaceDef - This callback is called after a namespace is
9255/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9256void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9257 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9258 assert(Namespc && "Invalid parameter, expected NamespaceDecl")((Namespc && "Invalid parameter, expected NamespaceDecl"
) ? static_cast<void> (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9258, __PRETTY_FUNCTION__))
;
9259 Namespc->setRBraceLoc(RBrace);
9260 PopDeclContext();
9261 if (Namespc->hasAttr<VisibilityAttr>())
9262 PopPragmaVisibility(true, RBrace);
9263 // If this namespace contains an export-declaration, export it now.
9264 if (DeferredExportedNamespaces.erase(Namespc))
9265 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9266}
9267
9268CXXRecordDecl *Sema::getStdBadAlloc() const {
9269 return cast_or_null<CXXRecordDecl>(
9270 StdBadAlloc.get(Context.getExternalSource()));
9271}
9272
9273EnumDecl *Sema::getStdAlignValT() const {
9274 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9275}
9276
9277NamespaceDecl *Sema::getStdNamespace() const {
9278 return cast_or_null<NamespaceDecl>(
9279 StdNamespace.get(Context.getExternalSource()));
9280}
9281
9282NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9283 if (!StdExperimentalNamespaceCache) {
9284 if (auto Std = getStdNamespace()) {
9285 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9286 SourceLocation(), LookupNamespaceName);
9287 if (!LookupQualifiedName(Result, Std) ||
9288 !(StdExperimentalNamespaceCache =
9289 Result.getAsSingle<NamespaceDecl>()))
9290 Result.suppressDiagnostics();
9291 }
9292 }
9293 return StdExperimentalNamespaceCache;
9294}
9295
9296namespace {
9297
9298enum UnsupportedSTLSelect {
9299 USS_InvalidMember,
9300 USS_MissingMember,
9301 USS_NonTrivial,
9302 USS_Other
9303};
9304
9305struct InvalidSTLDiagnoser {
9306 Sema &S;
9307 SourceLocation Loc;
9308 QualType TyForDiags;
9309
9310 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9311 const VarDecl *VD = nullptr) {
9312 {
9313 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9314 << TyForDiags << ((int)Sel);
9315 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9316 assert(!Name.empty())((!Name.empty()) ? static_cast<void> (0) : __assert_fail
("!Name.empty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9316, __PRETTY_FUNCTION__))
;
9317 D << Name;
9318 }
9319 }
9320 if (Sel == USS_InvalidMember) {
9321 S.Diag(VD->getLocation(), diag::note_var_declared_here)
9322 << VD << VD->getSourceRange();
9323 }
9324 return QualType();
9325 }
9326};
9327} // namespace
9328
9329QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9330 SourceLocation Loc) {
9331 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9332, __PRETTY_FUNCTION__))
9332 "Looking for comparison category type outside of C++.")((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9332, __PRETTY_FUNCTION__))
;
9333
9334 // Check if we've already successfully checked the comparison category type
9335 // before. If so, skip checking it again.
9336 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9337 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9338 return Info->getType();
9339
9340 // If lookup failed
9341 if (!Info) {
9342 std::string NameForDiags = "std::";
9343 NameForDiags += ComparisonCategories::getCategoryString(Kind);
9344 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9345 << NameForDiags;
9346 return QualType();
9347 }
9348
9349 assert(Info->Kind == Kind)((Info->Kind == Kind) ? static_cast<void> (0) : __assert_fail
("Info->Kind == Kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9349, __PRETTY_FUNCTION__))
;
9350 assert(Info->Record)((Info->Record) ? static_cast<void> (0) : __assert_fail
("Info->Record", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9350, __PRETTY_FUNCTION__))
;
9351
9352 // Update the Record decl in case we encountered a forward declaration on our
9353 // first pass. FIXME: This is a bit of a hack.
9354 if (Info->Record->hasDefinition())
9355 Info->Record = Info->Record->getDefinition();
9356
9357 // Use an elaborated type for diagnostics which has a name containing the
9358 // prepended 'std' namespace but not any inline namespace names.
9359 QualType TyForDiags = [&]() {
9360 auto *NNS =
9361 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9362 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9363 }();
9364
9365 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9366 return QualType();
9367
9368 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9369
9370 if (!Info->Record->isTriviallyCopyable())
9371 return UnsupportedSTLError(USS_NonTrivial);
9372
9373 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9374 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9375 // Tolerate empty base classes.
9376 if (Base->isEmpty())
9377 continue;
9378 // Reject STL implementations which have at least one non-empty base.
9379 return UnsupportedSTLError();
9380 }
9381
9382 // Check that the STL has implemented the types using a single integer field.
9383 // This expectation allows better codegen for builtin operators. We require:
9384 // (1) The class has exactly one field.
9385 // (2) The field is an integral or enumeration type.
9386 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9387 if (std::distance(FIt, FEnd) != 1 ||
9388 !FIt->getType()->isIntegralOrEnumerationType()) {
9389 return UnsupportedSTLError();
9390 }
9391
9392 // Build each of the require values and store them in Info.
9393 for (ComparisonCategoryResult CCR :
9394 ComparisonCategories::getPossibleResultsForType(Kind)) {
9395 StringRef MemName = ComparisonCategories::getResultString(CCR);
9396 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9397
9398 if (!ValInfo)
9399 return UnsupportedSTLError(USS_MissingMember, MemName);
9400
9401 VarDecl *VD = ValInfo->VD;
9402 assert(VD && "should not be null!")((VD && "should not be null!") ? static_cast<void>
(0) : __assert_fail ("VD && \"should not be null!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9402, __PRETTY_FUNCTION__))
;
9403
9404 // Attempt to diagnose reasons why the STL definition of this type
9405 // might be foobar, including it failing to be a constant expression.
9406 // TODO Handle more ways the lookup or result can be invalid.
9407 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9408 !VD->checkInitIsICE())
9409 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9410
9411 // Attempt to evaluate the var decl as a constant expression and extract
9412 // the value of its first field as a ICE. If this fails, the STL
9413 // implementation is not supported.
9414 if (!ValInfo->hasValidIntValue())
9415 return UnsupportedSTLError();
9416
9417 MarkVariableReferenced(Loc, VD);
9418 }
9419
9420 // We've successfully built the required types and expressions. Update
9421 // the cache and return the newly cached value.
9422 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9423 return Info->getType();
9424}
9425
9426/// Retrieve the special "std" namespace, which may require us to
9427/// implicitly define the namespace.
9428NamespaceDecl *Sema::getOrCreateStdNamespace() {
9429 if (!StdNamespace) {
9430 // The "std" namespace has not yet been defined, so build one implicitly.
9431 StdNamespace = NamespaceDecl::Create(Context,
9432 Context.getTranslationUnitDecl(),
9433 /*Inline=*/false,
9434 SourceLocation(), SourceLocation(),
9435 &PP.getIdentifierTable().get("std"),
9436 /*PrevDecl=*/nullptr);
9437 getStdNamespace()->setImplicit(true);
9438 }
9439
9440 return getStdNamespace();
9441}
9442
9443bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9444 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9445, __PRETTY_FUNCTION__))
9445 "Looking for std::initializer_list outside of C++.")((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9445, __PRETTY_FUNCTION__))
;
9446
9447 // We're looking for implicit instantiations of
9448 // template <typename E> class std::initializer_list.
9449
9450 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9451 return false;
9452
9453 ClassTemplateDecl *Template = nullptr;
9454 const TemplateArgument *Arguments = nullptr;
9455
9456 if (const RecordType *RT = Ty->getAs<RecordType>()) {
9457
9458 ClassTemplateSpecializationDecl *Specialization =
9459 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9460 if (!Specialization)
9461 return false;
9462
9463 Template = Specialization->getSpecializedTemplate();
9464 Arguments = Specialization->getTemplateArgs().data();
9465 } else if (const TemplateSpecializationType *TST =
9466 Ty->getAs<TemplateSpecializationType>()) {
9467 Template = dyn_cast_or_null<ClassTemplateDecl>(
9468 TST->getTemplateName().getAsTemplateDecl());
9469 Arguments = TST->getArgs();
9470 }
9471 if (!Template)
9472 return false;
9473
9474 if (!StdInitializerList) {
9475 // Haven't recognized std::initializer_list yet, maybe this is it.
9476 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9477 if (TemplateClass->getIdentifier() !=
9478 &PP.getIdentifierTable().get("initializer_list") ||
9479 !getStdNamespace()->InEnclosingNamespaceSetOf(
9480 TemplateClass->getDeclContext()))
9481 return false;
9482 // This is a template called std::initializer_list, but is it the right
9483 // template?
9484 TemplateParameterList *Params = Template->getTemplateParameters();
9485 if (Params->getMinRequiredArguments() != 1)
9486 return false;
9487 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9488 return false;
9489
9490 // It's the right template.
9491 StdInitializerList = Template;
9492 }
9493
9494 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9495 return false;
9496
9497 // This is an instance of std::initializer_list. Find the argument type.
9498 if (Element)
9499 *Element = Arguments[0].getAsType();
9500 return true;
9501}
9502
9503static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9504 NamespaceDecl *Std = S.getStdNamespace();
9505 if (!Std) {
9506 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9507 return nullptr;
9508 }
9509
9510 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9511 Loc, Sema::LookupOrdinaryName);
9512 if (!S.LookupQualifiedName(Result, Std)) {
9513 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9514 return nullptr;
9515 }
9516 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9517 if (!Template) {
9518 Result.suppressDiagnostics();
9519 // We found something weird. Complain about the first thing we found.
9520 NamedDecl *Found = *Result.begin();
9521 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9522 return nullptr;
9523 }
9524
9525 // We found some template called std::initializer_list. Now verify that it's
9526 // correct.
9527 TemplateParameterList *Params = Template->getTemplateParameters();
9528 if (Params->getMinRequiredArguments() != 1 ||
9529 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9530 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9531 return nullptr;
9532 }
9533
9534 return Template;
9535}
9536
9537QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9538 if (!StdInitializerList) {
9539 StdInitializerList = LookupStdInitializerList(*this, Loc);
9540 if (!StdInitializerList)
9541 return QualType();
9542 }
9543
9544 TemplateArgumentListInfo Args(Loc, Loc);
9545 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9546 Context.getTrivialTypeSourceInfo(Element,
9547 Loc)));
9548 return Context.getCanonicalType(
9549 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9550}
9551
9552bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9553 // C++ [dcl.init.list]p2:
9554 // A constructor is an initializer-list constructor if its first parameter
9555 // is of type std::initializer_list<E> or reference to possibly cv-qualified
9556 // std::initializer_list<E> for some type E, and either there are no other
9557 // parameters or else all other parameters have default arguments.
9558 if (Ctor->getNumParams() < 1 ||
9559 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9560 return false;
9561
9562 QualType ArgType = Ctor->getParamDecl(0)->getType();
9563 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9564 ArgType = RT->getPointeeType().getUnqualifiedType();
9565
9566 return isStdInitializerList(ArgType, nullptr);
9567}
9568
9569/// Determine whether a using statement is in a context where it will be
9570/// apply in all contexts.
9571static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9572 switch (CurContext->getDeclKind()) {
9573 case Decl::TranslationUnit:
9574 return true;
9575 case Decl::LinkageSpec:
9576 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9577 default:
9578 return false;
9579 }
9580}
9581
9582namespace {
9583
9584// Callback to only accept typo corrections that are namespaces.
9585class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9586public:
9587 bool ValidateCandidate(const TypoCorrection &candidate) override {
9588 if (NamedDecl *ND = candidate.getCorrectionDecl())
9589 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9590 return false;
9591 }
9592
9593 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9594 return std::make_unique<NamespaceValidatorCCC>(*this);
9595 }
9596};
9597
9598}
9599
9600static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9601 CXXScopeSpec &SS,
9602 SourceLocation IdentLoc,
9603 IdentifierInfo *Ident) {
9604 R.clear();
9605 NamespaceValidatorCCC CCC{};
9606 if (TypoCorrection Corrected =
9607 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9608 Sema::CTK_ErrorRecovery)) {
9609 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9610 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9611 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9612 Ident->getName().equals(CorrectedStr);
9613 S.diagnoseTypo(Corrected,
9614 S.PDiag(diag::err_using_directive_member_suggest)
9615 << Ident << DC << DroppedSpecifier << SS.getRange(),
9616 S.PDiag(diag::note_namespace_defined_here));
9617 } else {
9618 S.diagnoseTypo(Corrected,
9619 S.PDiag(diag::err_using_directive_suggest) << Ident,
9620 S.PDiag(diag::note_namespace_defined_here));
9621 }
9622 R.addDecl(Corrected.getFoundDecl());
9623 return true;
9624 }
9625 return false;
9626}
9627
9628Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9629 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9630 SourceLocation IdentLoc,
9631 IdentifierInfo *NamespcName,
9632 const ParsedAttributesView &AttrList) {
9633 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast
<void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9633, __PRETTY_FUNCTION__))
;
9634 assert(NamespcName && "Invalid NamespcName.")((NamespcName && "Invalid NamespcName.") ? static_cast
<void> (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9634, __PRETTY_FUNCTION__))
;
9635 assert(IdentLoc.isValid() && "Invalid NamespceName location.")((IdentLoc.isValid() && "Invalid NamespceName location."
) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9635, __PRETTY_FUNCTION__))
;
9636
9637 // This can only happen along a recovery path.
9638 while (S->isTemplateParamScope())
9639 S = S->getParent();
9640 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope."
) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9640, __PRETTY_FUNCTION__))
;
9641
9642 UsingDirectiveDecl *UDir = nullptr;
9643 NestedNameSpecifier *Qualifier = nullptr;
9644 if (SS.isSet())
9645 Qualifier = SS.getScopeRep();
9646
9647 // Lookup namespace name.
9648 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9649 LookupParsedName(R, S, &SS);
9650 if (R.isAmbiguous())
9651 return nullptr;
9652
9653 if (R.empty()) {
9654 R.clear();
9655 // Allow "using namespace std;" or "using namespace ::std;" even if
9656 // "std" hasn't been defined yet, for GCC compatibility.
9657 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9658 NamespcName->isStr("std")) {
9659 Diag(IdentLoc, diag::ext_using_undefined_std);
9660 R.addDecl(getOrCreateStdNamespace());
9661 R.resolveKind();
9662 }
9663 // Otherwise, attempt typo correction.
9664 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9665 }
9666
9667 if (!R.empty()) {
9668 NamedDecl *Named = R.getRepresentativeDecl();
9669 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9670 assert(NS && "expected namespace decl")((NS && "expected namespace decl") ? static_cast<void
> (0) : __assert_fail ("NS && \"expected namespace decl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9670, __PRETTY_FUNCTION__))
;
9671
9672 // The use of a nested name specifier may trigger deprecation warnings.
9673 DiagnoseUseOfDecl(Named, IdentLoc);
9674
9675 // C++ [namespace.udir]p1:
9676 // A using-directive specifies that the names in the nominated
9677 // namespace can be used in the scope in which the
9678 // using-directive appears after the using-directive. During
9679 // unqualified name lookup (3.4.1), the names appear as if they
9680 // were declared in the nearest enclosing namespace which
9681 // contains both the using-directive and the nominated
9682 // namespace. [Note: in this context, "contains" means "contains
9683 // directly or indirectly". ]
9684
9685 // Find enclosing context containing both using-directive and
9686 // nominated namespace.
9687 DeclContext *CommonAncestor = NS;
9688 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9689 CommonAncestor = CommonAncestor->getParent();
9690
9691 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9692 SS.getWithLocInContext(Context),
9693 IdentLoc, Named, CommonAncestor);
9694
9695 if (IsUsingDirectiveInToplevelContext(CurContext) &&
9696 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9697 Diag(IdentLoc, diag::warn_using_directive_in_header);
9698 }
9699
9700 PushUsingDirective(S, UDir);
9701 } else {
9702 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9703 }
9704
9705 if (UDir)
9706 ProcessDeclAttributeList(S, UDir, AttrList);
9707
9708 return UDir;
9709}
9710
9711void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9712 // If the scope has an associated entity and the using directive is at
9713 // namespace or translation unit scope, add the UsingDirectiveDecl into
9714 // its lookup structure so qualified name lookup can find it.
9715 DeclContext *Ctx = S->getEntity();
9716 if (Ctx && !Ctx->isFunctionOrMethod())
9717 Ctx->addDecl(UDir);
9718 else
9719 // Otherwise, it is at block scope. The using-directives will affect lookup
9720 // only to the end of the scope.
9721 S->PushUsingDirective(UDir);
9722}
9723
9724Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9725 SourceLocation UsingLoc,
9726 SourceLocation TypenameLoc, CXXScopeSpec &SS,
9727 UnqualifiedId &Name,
9728 SourceLocation EllipsisLoc,
9729 const ParsedAttributesView &AttrList) {
9730 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope."
) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9730, __PRETTY_FUNCTION__))
;
9731
9732 if (SS.isEmpty()) {
9733 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9734 return nullptr;
9735 }
9736
9737 switch (Name.getKind()) {
9738 case UnqualifiedIdKind::IK_ImplicitSelfParam:
9739 case UnqualifiedIdKind::IK_Identifier:
9740 case UnqualifiedIdKind::IK_OperatorFunctionId:
9741 case UnqualifiedIdKind::IK_LiteralOperatorId:
9742 case UnqualifiedIdKind::IK_ConversionFunctionId:
9743 break;
9744
9745 case UnqualifiedIdKind::IK_ConstructorName:
9746 case UnqualifiedIdKind::IK_ConstructorTemplateId:
9747 // C++11 inheriting constructors.
9748 Diag(Name.getBeginLoc(),
9749 getLangOpts().CPlusPlus11
9750 ? diag::warn_cxx98_compat_using_decl_constructor
9751 : diag::err_using_decl_constructor)
9752 << SS.getRange();
9753
9754 if (getLangOpts().CPlusPlus11) break;
9755
9756 return nullptr;
9757
9758 case UnqualifiedIdKind::IK_DestructorName:
9759 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9760 return nullptr;
9761
9762 case UnqualifiedIdKind::IK_TemplateId:
9763 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9764 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9765 return nullptr;
9766
9767 case UnqualifiedIdKind::IK_DeductionGuideName:
9768 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9768)
;
9769 }
9770
9771 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9772 DeclarationName TargetName = TargetNameInfo.getName();
9773 if (!TargetName)
9774 return nullptr;
9775
9776 // Warn about access declarations.
9777 if (UsingLoc.isInvalid()) {
9778 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9779 ? diag::err_access_decl
9780 : diag::warn_access_decl_deprecated)
9781 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9782 }
9783
9784 if (EllipsisLoc.isInvalid()) {
9785 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9786 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9787 return nullptr;
9788 } else {
9789 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9790 !TargetNameInfo.containsUnexpandedParameterPack()) {
9791 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9792 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9793 EllipsisLoc = SourceLocation();
9794 }
9795 }
9796
9797 NamedDecl *UD =
9798 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9799 SS, TargetNameInfo, EllipsisLoc, AttrList,
9800 /*IsInstantiation*/false);
9801 if (UD)
9802 PushOnScopeChains(UD, S, /*AddToContext*/ false);
9803
9804 return UD;
9805}
9806
9807/// Determine whether a using declaration considers the given
9808/// declarations as "equivalent", e.g., if they are redeclarations of
9809/// the same entity or are both typedefs of the same type.
9810static bool
9811IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9812 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9813 return true;
9814
9815 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9816 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9817 return Context.hasSameType(TD1->getUnderlyingType(),
9818 TD2->getUnderlyingType());
9819
9820 return false;
9821}
9822
9823
9824/// Determines whether to create a using shadow decl for a particular
9825/// decl, given the set of decls existing prior to this using lookup.
9826bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9827 const LookupResult &Previous,
9828 UsingShadowDecl *&PrevShadow) {
9829 // Diagnose finding a decl which is not from a base class of the
9830 // current class. We do this now because there are cases where this
9831 // function will silently decide not to build a shadow decl, which
9832 // will pre-empt further diagnostics.
9833 //
9834 // We don't need to do this in C++11 because we do the check once on
9835 // the qualifier.
9836 //
9837 // FIXME: diagnose the following if we care enough:
9838 // struct A { int foo; };
9839 // struct B : A { using A::foo; };
9840 // template <class T> struct C : A {};
9841 // template <class T> struct D : C<T> { using B::foo; } // <---
9842 // This is invalid (during instantiation) in C++03 because B::foo
9843 // resolves to the using decl in B, which is not a base class of D<T>.
9844 // We can't diagnose it immediately because C<T> is an unknown
9845 // specialization. The UsingShadowDecl in D<T> then points directly
9846 // to A::foo, which will look well-formed when we instantiate.
9847 // The right solution is to not collapse the shadow-decl chain.
9848 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9849 DeclContext *OrigDC = Orig->getDeclContext();
9850
9851 // Handle enums and anonymous structs.
9852 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9853 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9854 while (OrigRec->isAnonymousStructOrUnion())
9855 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9856
9857 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9858 if (OrigDC == CurContext) {
9859 Diag(Using->getLocation(),
9860 diag::err_using_decl_nested_name_specifier_is_current_class)
9861 << Using->getQualifierLoc().getSourceRange();
9862 Diag(Orig->getLocation(), diag::note_using_decl_target);
9863 Using->setInvalidDecl();
9864 return true;
9865 }
9866
9867 Diag(Using->getQualifierLoc().getBeginLoc(),
9868 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9869 << Using->getQualifier()
9870 << cast<CXXRecordDecl>(CurContext)
9871 << Using->getQualifierLoc().getSourceRange();
9872 Diag(Orig->getLocation(), diag::note_using_decl_target);
9873 Using->setInvalidDecl();
9874 return true;
9875 }
9876 }
9877
9878 if (Previous.empty()) return false;
9879
9880 NamedDecl *Target = Orig;
9881 if (isa<UsingShadowDecl>(Target))
9882 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9883
9884 // If the target happens to be one of the previous declarations, we
9885 // don't have a conflict.
9886 //
9887 // FIXME: but we might be increasing its access, in which case we
9888 // should redeclare it.
9889 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9890 bool FoundEquivalentDecl = false;
9891 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9892 I != E; ++I) {
9893 NamedDecl *D = (*I)->getUnderlyingDecl();
9894 // We can have UsingDecls in our Previous results because we use the same
9895 // LookupResult for checking whether the UsingDecl itself is a valid
9896 // redeclaration.
9897 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9898 continue;
9899
9900 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9901 // C++ [class.mem]p19:
9902 // If T is the name of a class, then [every named member other than
9903 // a non-static data member] shall have a name different from T
9904 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9905 !isa<IndirectFieldDecl>(Target) &&
9906 !isa<UnresolvedUsingValueDecl>(Target) &&
9907 DiagnoseClassNameShadow(
9908 CurContext,
9909 DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9910 return true;
9911 }
9912
9913 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9914 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9915 PrevShadow = Shadow;
9916 FoundEquivalentDecl = true;
9917 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9918 // We don't conflict with an existing using shadow decl of an equivalent
9919 // declaration, but we're not a redeclaration of it.
9920 FoundEquivalentDecl = true;
9921 }
9922
9923 if (isVisible(D))
9924 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9925 }
9926
9927 if (FoundEquivalentDecl)
9928 return false;
9929
9930 if (FunctionDecl *FD = Target->getAsFunction()) {
9931 NamedDecl *OldDecl = nullptr;
9932 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9933 /*IsForUsingDecl*/ true)) {
9934 case Ovl_Overload:
9935 return false;
9936
9937 case Ovl_NonFunction:
9938 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9939 break;
9940
9941 // We found a decl with the exact signature.
9942 case Ovl_Match:
9943 // If we're in a record, we want to hide the target, so we
9944 // return true (without a diagnostic) to tell the caller not to
9945 // build a shadow decl.
9946 if (CurContext->isRecord())
9947 return true;
9948
9949 // If we're not in a record, this is an error.
9950 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9951 break;
9952 }
9953
9954 Diag(Target->getLocation(), diag::note_using_decl_target);
9955 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9956 Using->setInvalidDecl();
9957 return true;
9958 }
9959
9960 // Target is not a function.
9961
9962 if (isa<TagDecl>(Target)) {
9963 // No conflict between a tag and a non-tag.
9964 if (!Tag) return false;
9965
9966 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9967 Diag(Target->getLocation(), diag::note_using_decl_target);
9968 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9969 Using->setInvalidDecl();
9970 return true;
9971 }
9972
9973 // No conflict between a tag and a non-tag.
9974 if (!NonTag) return false;
9975
9976 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9977 Diag(Target->getLocation(), diag::note_using_decl_target);
9978 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9979 Using->setInvalidDecl();
9980 return true;
9981}
9982
9983/// Determine whether a direct base class is a virtual base class.
9984static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9985 if (!Derived->getNumVBases())
9986 return false;
9987 for (auto &B : Derived->bases())
9988 if (B.getType()->getAsCXXRecordDecl() == Base)
9989 return B.isVirtual();
9990 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 9990)
;
9991}
9992
9993/// Builds a shadow declaration corresponding to a 'using' declaration.
9994UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9995 UsingDecl *UD,
9996 NamedDecl *Orig,
9997 UsingShadowDecl *PrevDecl) {
9998 // If we resolved to another shadow declaration, just coalesce them.
9999 NamedDecl *Target = Orig;
10000 if (isa<UsingShadowDecl>(Target)) {
10001 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
10002 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")((!isa<UsingShadowDecl>(Target) && "nested shadow declaration"
) ? static_cast<void> (0) : __assert_fail ("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10002, __PRETTY_FUNCTION__))
;
10003 }
10004
10005 NamedDecl *NonTemplateTarget = Target;
10006 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
10007 NonTemplateTarget = TargetTD->getTemplatedDecl();
10008
10009 UsingShadowDecl *Shadow;
10010 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
10011 bool IsVirtualBase =
10012 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
10013 UD->getQualifier()->getAsRecordDecl());
10014 Shadow = ConstructorUsingShadowDecl::Create(
10015 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
10016 } else {
10017 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
10018 Target);
10019 }
10020 UD->addShadowDecl(Shadow);
10021
10022 Shadow->setAccess(UD->getAccess());
10023 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
10024 Shadow->setInvalidDecl();
10025
10026 Shadow->setPreviousDecl(PrevDecl);
10027
10028 if (S)
10029 PushOnScopeChains(Shadow, S);
10030 else
10031 CurContext->addDecl(Shadow);
10032
10033
10034 return Shadow;
10035}
10036
10037/// Hides a using shadow declaration. This is required by the current
10038/// using-decl implementation when a resolvable using declaration in a
10039/// class is followed by a declaration which would hide or override
10040/// one or more of the using decl's targets; for example:
10041///
10042/// struct Base { void foo(int); };
10043/// struct Derived : Base {
10044/// using Base::foo;
10045/// void foo(int);
10046/// };
10047///
10048/// The governing language is C++03 [namespace.udecl]p12:
10049///
10050/// When a using-declaration brings names from a base class into a
10051/// derived class scope, member functions in the derived class
10052/// override and/or hide member functions with the same name and
10053/// parameter types in a base class (rather than conflicting).
10054///
10055/// There are two ways to implement this:
10056/// (1) optimistically create shadow decls when they're not hidden
10057/// by existing declarations, or
10058/// (2) don't create any shadow decls (or at least don't make them
10059/// visible) until we've fully parsed/instantiated the class.
10060/// The problem with (1) is that we might have to retroactively remove
10061/// a shadow decl, which requires several O(n) operations because the
10062/// decl structures are (very reasonably) not designed for removal.
10063/// (2) avoids this but is very fiddly and phase-dependent.
10064void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
10065 if (Shadow->getDeclName().getNameKind() ==
10066 DeclarationName::CXXConversionFunctionName)
10067 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
10068
10069 // Remove it from the DeclContext...
10070 Shadow->getDeclContext()->removeDecl(Shadow);
10071
10072 // ...and the scope, if applicable...
10073 if (S) {
10074 S->RemoveDecl(Shadow);
10075 IdResolver.RemoveDecl(Shadow);
10076 }
10077
10078 // ...and the using decl.
10079 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
10080
10081 // TODO: complain somehow if Shadow was used. It shouldn't
10082 // be possible for this to happen, because...?
10083}
10084
10085/// Find the base specifier for a base class with the given type.
10086static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
10087 QualType DesiredBase,
10088 bool &AnyDependentBases) {
10089 // Check whether the named type is a direct base class.
10090 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
10091 .getUnqualifiedType();
10092 for (auto &Base : Derived->bases()) {
10093 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
10094 if (CanonicalDesiredBase == BaseType)
10095 return &Base;
10096 if (BaseType->isDependentType())
10097 AnyDependentBases = true;
10098 }
10099 return nullptr;
10100}
10101
10102namespace {
10103class UsingValidatorCCC final : public CorrectionCandidateCallback {
10104public:
10105 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
10106 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
10107 : HasTypenameKeyword(HasTypenameKeyword),
10108 IsInstantiation(IsInstantiation), OldNNS(NNS),
10109 RequireMemberOf(RequireMemberOf) {}
10110
10111 bool ValidateCandidate(const TypoCorrection &Candidate) override {
10112 NamedDecl *ND = Candidate.getCorrectionDecl();
10113
10114 // Keywords are not valid here.
10115 if (!ND || isa<NamespaceDecl>(ND))
10116 return false;
10117
10118 // Completely unqualified names are invalid for a 'using' declaration.
10119 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
10120 return false;
10121
10122 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
10123 // reject.
10124
10125 if (RequireMemberOf) {
10126 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10127 if (FoundRecord && FoundRecord->isInjectedClassName()) {
10128 // No-one ever wants a using-declaration to name an injected-class-name
10129 // of a base class, unless they're declaring an inheriting constructor.
10130 ASTContext &Ctx = ND->getASTContext();
10131 if (!Ctx.getLangOpts().CPlusPlus11)
10132 return false;
10133 QualType FoundType = Ctx.getRecordType(FoundRecord);
10134
10135 // Check that the injected-class-name is named as a member of its own
10136 // type; we don't want to suggest 'using Derived::Base;', since that
10137 // means something else.
10138 NestedNameSpecifier *Specifier =
10139 Candidate.WillReplaceSpecifier()
10140 ? Candidate.getCorrectionSpecifier()
10141 : OldNNS;
10142 if (!Specifier->getAsType() ||
10143 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
10144 return false;
10145
10146 // Check that this inheriting constructor declaration actually names a
10147 // direct base class of the current class.
10148 bool AnyDependentBases = false;
10149 if (!findDirectBaseWithType(RequireMemberOf,
10150 Ctx.getRecordType(FoundRecord),
10151 AnyDependentBases) &&
10152 !AnyDependentBases)
10153 return false;
10154 } else {
10155 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
10156 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
10157 return false;
10158
10159 // FIXME: Check that the base class member is accessible?
10160 }
10161 } else {
10162 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10163 if (FoundRecord && FoundRecord->isInjectedClassName())
10164 return false;
10165 }
10166
10167 if (isa<TypeDecl>(ND))
10168 return HasTypenameKeyword || !IsInstantiation;
10169
10170 return !HasTypenameKeyword;
10171 }
10172
10173 std::unique_ptr<CorrectionCandidateCallback> clone() override {
10174 return std::make_unique<UsingValidatorCCC>(*this);
10175 }
10176
10177private:
10178 bool HasTypenameKeyword;
10179 bool IsInstantiation;
10180 NestedNameSpecifier *OldNNS;
10181 CXXRecordDecl *RequireMemberOf;
10182};
10183} // end anonymous namespace
10184
10185/// Builds a using declaration.
10186///
10187/// \param IsInstantiation - Whether this call arises from an
10188/// instantiation of an unresolved using declaration. We treat
10189/// the lookup differently for these declarations.
10190NamedDecl *Sema::BuildUsingDeclaration(
10191 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
10192 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
10193 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
10194 const ParsedAttributesView &AttrList, bool IsInstantiation) {
10195 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast
<void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10195, __PRETTY_FUNCTION__))
;
10196 SourceLocation IdentLoc = NameInfo.getLoc();
10197 assert(IdentLoc.isValid() && "Invalid TargetName location.")((IdentLoc.isValid() && "Invalid TargetName location."
) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10197, __PRETTY_FUNCTION__))
;
10198
10199 // FIXME: We ignore attributes for now.
10200
10201 // For an inheriting constructor declaration, the name of the using
10202 // declaration is the name of a constructor in this class, not in the
10203 // base class.
10204 DeclarationNameInfo UsingName = NameInfo;
10205 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
10206 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
10207 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10208 Context.getCanonicalType(Context.getRecordType(RD))));
10209
10210 // Do the redeclaration lookup in the current scope.
10211 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10212 ForVisibleRedeclaration);
10213 Previous.setHideTags(false);
10214 if (S) {
10215 LookupName(Previous, S);
10216
10217 // It is really dumb that we have to do this.
10218 LookupResult::Filter F = Previous.makeFilter();
10219 while (F.hasNext()) {
10220 NamedDecl *D = F.next();
10221 if (!isDeclInScope(D, CurContext, S))
10222 F.erase();
10223 // If we found a local extern declaration that's not ordinarily visible,
10224 // and this declaration is being added to a non-block scope, ignore it.
10225 // We're only checking for scope conflicts here, not also for violations
10226 // of the linkage rules.
10227 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10228 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10229 F.erase();
10230 }
10231 F.done();
10232 } else {
10233 assert(IsInstantiation && "no scope in non-instantiation")((IsInstantiation && "no scope in non-instantiation")
? static_cast<void> (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10233, __PRETTY_FUNCTION__))
;
10234 if (CurContext->isRecord())
10235 LookupQualifiedName(Previous, CurContext);
10236 else {
10237 // No redeclaration check is needed here; in non-member contexts we
10238 // diagnosed all possible conflicts with other using-declarations when
10239 // building the template:
10240 //
10241 // For a dependent non-type using declaration, the only valid case is
10242 // if we instantiate to a single enumerator. We check for conflicts
10243 // between shadow declarations we introduce, and we check in the template
10244 // definition for conflicts between a non-type using declaration and any
10245 // other declaration, which together covers all cases.
10246 //
10247 // A dependent typename using declaration will never successfully
10248 // instantiate, since it will always name a class member, so we reject
10249 // that in the template definition.
10250 }
10251 }
10252
10253 // Check for invalid redeclarations.
10254 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10255 SS, IdentLoc, Previous))
10256 return nullptr;
10257
10258 // Check for bad qualifiers.
10259 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10260 IdentLoc))
10261 return nullptr;
10262
10263 DeclContext *LookupContext = computeDeclContext(SS);
10264 NamedDecl *D;
10265 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10266 if (!LookupContext || EllipsisLoc.isValid()) {
10267 if (HasTypenameKeyword) {
10268 // FIXME: not all declaration name kinds are legal here
10269 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10270 UsingLoc, TypenameLoc,
10271 QualifierLoc,
10272 IdentLoc, NameInfo.getName(),
10273 EllipsisLoc);
10274 } else {
10275 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10276 QualifierLoc, NameInfo, EllipsisLoc);
10277 }
10278 D->setAccess(AS);
10279 CurContext->addDecl(D);
10280 return D;
10281 }
10282
10283 auto Build = [&](bool Invalid) {
10284 UsingDecl *UD =
10285 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10286 UsingName, HasTypenameKeyword);
10287 UD->setAccess(AS);
10288 CurContext->addDecl(UD);
10289 UD->setInvalidDecl(Invalid);
10290 return UD;
10291 };
10292 auto BuildInvalid = [&]{ return Build(true); };
10293 auto BuildValid = [&]{ return Build(false); };
10294
10295 if (RequireCompleteDeclContext(SS, LookupContext))
10296 return BuildInvalid();
10297
10298 // Look up the target name.
10299 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10300
10301 // Unlike most lookups, we don't always want to hide tag
10302 // declarations: tag names are visible through the using declaration
10303 // even if hidden by ordinary names, *except* in a dependent context
10304 // where it's important for the sanity of two-phase lookup.
10305 if (!IsInstantiation)
10306 R.setHideTags(false);
10307
10308 // For the purposes of this lookup, we have a base object type
10309 // equal to that of the current context.
10310 if (CurContext->isRecord()) {
10311 R.setBaseObjectType(
10312 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10313 }
10314
10315 LookupQualifiedName(R, LookupContext);
10316
10317 // Try to correct typos if possible. If constructor name lookup finds no
10318 // results, that means the named class has no explicit constructors, and we
10319 // suppressed declaring implicit ones (probably because it's dependent or
10320 // invalid).
10321 if (R.empty() &&
10322 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10323 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10324 // it will believe that glibc provides a ::gets in cases where it does not,
10325 // and will try to pull it into namespace std with a using-declaration.
10326 // Just ignore the using-declaration in that case.
10327 auto *II = NameInfo.getName().getAsIdentifierInfo();
10328 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10329 CurContext->isStdNamespace() &&
10330 isa<TranslationUnitDecl>(LookupContext) &&
10331 getSourceManager().isInSystemHeader(UsingLoc))
10332 return nullptr;
10333 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10334 dyn_cast<CXXRecordDecl>(CurContext));
10335 if (TypoCorrection Corrected =
10336 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10337 CTK_ErrorRecovery)) {
10338 // We reject candidates where DroppedSpecifier == true, hence the
10339 // literal '0' below.
10340 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10341 << NameInfo.getName() << LookupContext << 0
10342 << SS.getRange());
10343
10344 // If we picked a correction with no attached Decl we can't do anything
10345 // useful with it, bail out.
10346 NamedDecl *ND = Corrected.getCorrectionDecl();
10347 if (!ND)
10348 return BuildInvalid();
10349
10350 // If we corrected to an inheriting constructor, handle it as one.
10351 auto *RD = dyn_cast<CXXRecordDecl>(ND);
10352 if (RD && RD->isInjectedClassName()) {
10353 // The parent of the injected class name is the class itself.
10354 RD = cast<CXXRecordDecl>(RD->getParent());
10355
10356 // Fix up the information we'll use to build the using declaration.
10357 if (Corrected.WillReplaceSpecifier()) {
10358 NestedNameSpecifierLocBuilder Builder;
10359 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10360 QualifierLoc.getSourceRange());
10361 QualifierLoc = Builder.getWithLocInContext(Context);
10362 }
10363
10364 // In this case, the name we introduce is the name of a derived class
10365 // constructor.
10366 auto *CurClass = cast<CXXRecordDecl>(CurContext);
10367 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10368 Context.getCanonicalType(Context.getRecordType(CurClass))));
10369 UsingName.setNamedTypeInfo(nullptr);
10370 for (auto *Ctor : LookupConstructors(RD))
10371 R.addDecl(Ctor);
10372 R.resolveKind();
10373 } else {
10374 // FIXME: Pick up all the declarations if we found an overloaded
10375 // function.
10376 UsingName.setName(ND->getDeclName());
10377 R.addDecl(ND);
10378 }
10379 } else {
10380 Diag(IdentLoc, diag::err_no_member)
10381 << NameInfo.getName() << LookupContext << SS.getRange();
10382 return BuildInvalid();
10383 }
10384 }
10385
10386 if (R.isAmbiguous())
10387 return BuildInvalid();
10388
10389 if (HasTypenameKeyword) {
10390 // If we asked for a typename and got a non-type decl, error out.
10391 if (!R.getAsSingle<TypeDecl>()) {
10392 Diag(IdentLoc, diag::err_using_typename_non_type);
10393 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10394 Diag((*I)->getUnderlyingDecl()->getLocation(),
10395 diag::note_using_decl_target);
10396 return BuildInvalid();
10397 }
10398 } else {
10399 // If we asked for a non-typename and we got a type, error out,
10400 // but only if this is an instantiation of an unresolved using
10401 // decl. Otherwise just silently find the type name.
10402 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10403 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10404 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10405 return BuildInvalid();
10406 }
10407 }
10408
10409 // C++14 [namespace.udecl]p6:
10410 // A using-declaration shall not name a namespace.
10411 if (R.getAsSingle<NamespaceDecl>()) {
10412 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10413 << SS.getRange();
10414 return BuildInvalid();
10415 }
10416
10417 // C++14 [namespace.udecl]p7:
10418 // A using-declaration shall not name a scoped enumerator.
10419 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10420 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10421 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10422 << SS.getRange();
10423 return BuildInvalid();
10424 }
10425 }
10426
10427 UsingDecl *UD = BuildValid();
10428
10429 // Some additional rules apply to inheriting constructors.
10430 if (UsingName.getName().getNameKind() ==
10431 DeclarationName::CXXConstructorName) {
10432 // Suppress access diagnostics; the access check is instead performed at the
10433 // point of use for an inheriting constructor.
10434 R.suppressDiagnostics();
10435 if (CheckInheritingConstructorUsingDecl(UD))
10436 return UD;
10437 }
10438
10439 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10440 UsingShadowDecl *PrevDecl = nullptr;
10441 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10442 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10443 }
10444
10445 return UD;
10446}
10447
10448NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10449 ArrayRef<NamedDecl *> Expansions) {
10450 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10452, __PRETTY_FUNCTION__))
10451 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10452, __PRETTY_FUNCTION__))
10452 isa<UsingPackDecl>(InstantiatedFrom))((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa
<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<
UsingPackDecl>(InstantiatedFrom)) ? static_cast<void>
(0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10452, __PRETTY_FUNCTION__))
;
10453
10454 auto *UPD =
10455 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10456 UPD->setAccess(InstantiatedFrom->getAccess());
10457 CurContext->addDecl(UPD);
10458 return UPD;
10459}
10460
10461/// Additional checks for a using declaration referring to a constructor name.
10462bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10463 assert(!UD->hasTypename() && "expecting a constructor name")((!UD->hasTypename() && "expecting a constructor name"
) ? static_cast<void> (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10463, __PRETTY_FUNCTION__))
;
10464
10465 const Type *SourceType = UD->getQualifier()->getAsType();
10466 assert(SourceType &&((SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10467, __PRETTY_FUNCTION__))
10467 "Using decl naming constructor doesn't have type in scope spec.")((SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10467, __PRETTY_FUNCTION__))
;
10468 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10469
10470 // Check whether the named type is a direct base class.
10471 bool AnyDependentBases = false;
10472 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10473 AnyDependentBases);
10474 if (!Base && !AnyDependentBases) {
10475 Diag(UD->getUsingLoc(),
10476 diag::err_using_decl_constructor_not_in_direct_base)
10477 << UD->getNameInfo().getSourceRange()
10478 << QualType(SourceType, 0) << TargetClass;
10479 UD->setInvalidDecl();
10480 return true;
10481 }
10482
10483 if (Base)
10484 Base->setInheritConstructors();
10485
10486 return false;
10487}
10488
10489/// Checks that the given using declaration is not an invalid
10490/// redeclaration. Note that this is checking only for the using decl
10491/// itself, not for any ill-formedness among the UsingShadowDecls.
10492bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10493 bool HasTypenameKeyword,
10494 const CXXScopeSpec &SS,
10495 SourceLocation NameLoc,
10496 const LookupResult &Prev) {
10497 NestedNameSpecifier *Qual = SS.getScopeRep();
10498
10499 // C++03 [namespace.udecl]p8:
10500 // C++0x [namespace.udecl]p10:
10501 // A using-declaration is a declaration and can therefore be used
10502 // repeatedly where (and only where) multiple declarations are
10503 // allowed.
10504 //
10505 // That's in non-member contexts.
10506 if (!CurContext->getRedeclContext()->isRecord()) {
10507 // A dependent qualifier outside a class can only ever resolve to an
10508 // enumeration type. Therefore it conflicts with any other non-type
10509 // declaration in the same scope.
10510 // FIXME: How should we check for dependent type-type conflicts at block
10511 // scope?
10512 if (Qual->isDependent() && !HasTypenameKeyword) {
10513 for (auto *D : Prev) {
10514 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10515 bool OldCouldBeEnumerator =
10516 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10517 Diag(NameLoc,
10518 OldCouldBeEnumerator ? diag::err_redefinition
10519 : diag::err_redefinition_different_kind)
10520 << Prev.getLookupName();
10521 Diag(D->getLocation(), diag::note_previous_definition);
10522 return true;
10523 }
10524 }
10525 }
10526 return false;
10527 }
10528
10529 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10530 NamedDecl *D = *I;
10531
10532 bool DTypename;
10533 NestedNameSpecifier *DQual;
10534 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10535 DTypename = UD->hasTypename();
10536 DQual = UD->getQualifier();
10537 } else if (UnresolvedUsingValueDecl *UD
10538 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10539 DTypename = false;
10540 DQual = UD->getQualifier();
10541 } else if (UnresolvedUsingTypenameDecl *UD
10542 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10543 DTypename = true;
10544 DQual = UD->getQualifier();
10545 } else continue;
10546
10547 // using decls differ if one says 'typename' and the other doesn't.
10548 // FIXME: non-dependent using decls?
10549 if (HasTypenameKeyword != DTypename) continue;
10550
10551 // using decls differ if they name different scopes (but note that
10552 // template instantiation can cause this check to trigger when it
10553 // didn't before instantiation).
10554 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10555 Context.getCanonicalNestedNameSpecifier(DQual))
10556 continue;
10557
10558 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10559 Diag(D->getLocation(), diag::note_using_decl) << 1;
10560 return true;
10561 }
10562
10563 return false;
10564}
10565
10566
10567/// Checks that the given nested-name qualifier used in a using decl
10568/// in the current context is appropriately related to the current
10569/// scope. If an error is found, diagnoses it and returns true.
10570bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10571 bool HasTypename,
10572 const CXXScopeSpec &SS,
10573 const DeclarationNameInfo &NameInfo,
10574 SourceLocation NameLoc) {
10575 DeclContext *NamedContext = computeDeclContext(SS);
10576
10577 if (!CurContext->isRecord()) {
10578 // C++03 [namespace.udecl]p3:
10579 // C++0x [namespace.udecl]p8:
10580 // A using-declaration for a class member shall be a member-declaration.
10581
10582 // If we weren't able to compute a valid scope, it might validly be a
10583 // dependent class scope or a dependent enumeration unscoped scope. If
10584 // we have a 'typename' keyword, the scope must resolve to a class type.
10585 if ((HasTypename && !NamedContext) ||
10586 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10587 auto *RD = NamedContext
10588 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10589 : nullptr;
10590 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10591 RD = nullptr;
10592
10593 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10594 << SS.getRange();
10595
10596 // If we have a complete, non-dependent source type, try to suggest a
10597 // way to get the same effect.
10598 if (!RD)
10599 return true;
10600
10601 // Find what this using-declaration was referring to.
10602 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10603 R.setHideTags(false);
10604 R.suppressDiagnostics();
10605 LookupQualifiedName(R, RD);
10606
10607 if (R.getAsSingle<TypeDecl>()) {
10608 if (getLangOpts().CPlusPlus11) {
10609 // Convert 'using X::Y;' to 'using Y = X::Y;'.
10610 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10611 << 0 // alias declaration
10612 << FixItHint::CreateInsertion(SS.getBeginLoc(),
10613 NameInfo.getName().getAsString() +
10614 " = ");
10615 } else {
10616 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10617 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10618 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10619 << 1 // typedef declaration
10620 << FixItHint::CreateReplacement(UsingLoc, "typedef")
10621 << FixItHint::CreateInsertion(
10622 InsertLoc, " " + NameInfo.getName().getAsString());
10623 }
10624 } else if (R.getAsSingle<VarDecl>()) {
10625 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10626 // repeating the type of the static data member here.
10627 FixItHint FixIt;
10628 if (getLangOpts().CPlusPlus11) {
10629 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10630 FixIt = FixItHint::CreateReplacement(
10631 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10632 }
10633
10634 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10635 << 2 // reference declaration
10636 << FixIt;
10637 } else if (R.getAsSingle<EnumConstantDecl>()) {
10638 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10639 // repeating the type of the enumeration here, and we can't do so if
10640 // the type is anonymous.
10641 FixItHint FixIt;
10642 if (getLangOpts().CPlusPlus11) {
10643 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10644 FixIt = FixItHint::CreateReplacement(
10645 UsingLoc,
10646 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10647 }
10648
10649 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10650 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10651 << FixIt;
10652 }
10653 return true;
10654 }
10655
10656 // Otherwise, this might be valid.
10657 return false;
10658 }
10659
10660 // The current scope is a record.
10661
10662 // If the named context is dependent, we can't decide much.
10663 if (!NamedContext) {
10664 // FIXME: in C++0x, we can diagnose if we can prove that the
10665 // nested-name-specifier does not refer to a base class, which is
10666 // still possible in some cases.
10667
10668 // Otherwise we have to conservatively report that things might be
10669 // okay.
10670 return false;
10671 }
10672
10673 if (!NamedContext->isRecord()) {
10674 // Ideally this would point at the last name in the specifier,
10675 // but we don't have that level of source info.
10676 Diag(SS.getRange().getBegin(),
10677 diag::err_using_decl_nested_name_specifier_is_not_class)
10678 << SS.getScopeRep() << SS.getRange();
10679 return true;
10680 }
10681
10682 if (!NamedContext->isDependentContext() &&
10683 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10684 return true;
10685
10686 if (getLangOpts().CPlusPlus11) {
10687 // C++11 [namespace.udecl]p3:
10688 // In a using-declaration used as a member-declaration, the
10689 // nested-name-specifier shall name a base class of the class
10690 // being defined.
10691
10692 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10693 cast<CXXRecordDecl>(NamedContext))) {
10694 if (CurContext == NamedContext) {
10695 Diag(NameLoc,
10696 diag::err_using_decl_nested_name_specifier_is_current_class)
10697 << SS.getRange();
10698 return true;
10699 }
10700
10701 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10702 Diag(SS.getRange().getBegin(),
10703 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10704 << SS.getScopeRep()
10705 << cast<CXXRecordDecl>(CurContext)
10706 << SS.getRange();
10707 }
10708 return true;
10709 }
10710
10711 return false;
10712 }
10713
10714 // C++03 [namespace.udecl]p4:
10715 // A using-declaration used as a member-declaration shall refer
10716 // to a member of a base class of the class being defined [etc.].
10717
10718 // Salient point: SS doesn't have to name a base class as long as
10719 // lookup only finds members from base classes. Therefore we can
10720 // diagnose here only if we can prove that that can't happen,
10721 // i.e. if the class hierarchies provably don't intersect.
10722
10723 // TODO: it would be nice if "definitely valid" results were cached
10724 // in the UsingDecl and UsingShadowDecl so that these checks didn't
10725 // need to be repeated.
10726
10727 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10728 auto Collect = [&Bases](const CXXRecordDecl *Base) {
10729 Bases.insert(Base);
10730 return true;
10731 };
10732
10733 // Collect all bases. Return false if we find a dependent base.
10734 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10735 return false;
10736
10737 // Returns true if the base is dependent or is one of the accumulated base
10738 // classes.
10739 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10740 return !Bases.count(Base);
10741 };
10742
10743 // Return false if the class has a dependent base or if it or one
10744 // of its bases is present in the base set of the current context.
10745 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10746 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10747 return false;
10748
10749 Diag(SS.getRange().getBegin(),
10750 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10751 << SS.getScopeRep()
10752 << cast<CXXRecordDecl>(CurContext)
10753 << SS.getRange();
10754
10755 return true;
10756}
10757
10758Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10759 MultiTemplateParamsArg TemplateParamLists,
10760 SourceLocation UsingLoc, UnqualifiedId &Name,
10761 const ParsedAttributesView &AttrList,
10762 TypeResult Type, Decl *DeclFromDeclSpec) {
10763 // Skip up to the relevant declaration scope.
10764 while (S->isTemplateParamScope())
10765 S = S->getParent();
10766 assert((S->getFlags() & Scope::DeclScope) &&(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope"
) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10767, __PRETTY_FUNCTION__))
10767 "got alias-declaration outside of declaration scope")(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope"
) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10767, __PRETTY_FUNCTION__))
;
10768
10769 if (Type.isInvalid())
10770 return nullptr;
10771
10772 bool Invalid = false;
10773 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10774 TypeSourceInfo *TInfo = nullptr;
10775 GetTypeFromParser(Type.get(), &TInfo);
10776
10777 if (DiagnoseClassNameShadow(CurContext, NameInfo))
10778 return nullptr;
10779
10780 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10781 UPPC_DeclarationType)) {
10782 Invalid = true;
10783 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10784 TInfo->getTypeLoc().getBeginLoc());
10785 }
10786
10787 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10788 TemplateParamLists.size()
10789 ? forRedeclarationInCurContext()
10790 : ForVisibleRedeclaration);
10791 LookupName(Previous, S);
10792
10793 // Warn about shadowing the name of a template parameter.
10794 if (Previous.isSingleResult() &&
10795 Previous.getFoundDecl()->isTemplateParameter()) {
10796 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10797 Previous.clear();
10798 }
10799
10800 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10801, __PRETTY_FUNCTION__))
10801 "name in alias declaration must be an identifier")((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10801, __PRETTY_FUNCTION__))
;
10802 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10803 Name.StartLocation,
10804 Name.Identifier, TInfo);
10805
10806 NewTD->setAccess(AS);
10807
10808 if (Invalid)
10809 NewTD->setInvalidDecl();
10810
10811 ProcessDeclAttributeList(S, NewTD, AttrList);
10812 AddPragmaAttributes(S, NewTD);
10813
10814 CheckTypedefForVariablyModifiedType(S, NewTD);
10815 Invalid |= NewTD->isInvalidDecl();
10816
10817 bool Redeclaration = false;
10818
10819 NamedDecl *NewND;
10820 if (TemplateParamLists.size()) {
10821 TypeAliasTemplateDecl *OldDecl = nullptr;
10822 TemplateParameterList *OldTemplateParams = nullptr;
10823
10824 if (TemplateParamLists.size() != 1) {
10825 Diag(UsingLoc, diag::err_alias_template_extra_headers)
10826 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10827 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10828 }
10829 TemplateParameterList *TemplateParams = TemplateParamLists[0];
10830
10831 // Check that we can declare a template here.
10832 if (CheckTemplateDeclScope(S, TemplateParams))
10833 return nullptr;
10834
10835 // Only consider previous declarations in the same scope.
10836 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10837 /*ExplicitInstantiationOrSpecialization*/false);
10838 if (!Previous.empty()) {
10839 Redeclaration = true;
10840
10841 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10842 if (!OldDecl && !Invalid) {
10843 Diag(UsingLoc, diag::err_redefinition_different_kind)
10844 << Name.Identifier;
10845
10846 NamedDecl *OldD = Previous.getRepresentativeDecl();
10847 if (OldD->getLocation().isValid())
10848 Diag(OldD->getLocation(), diag::note_previous_definition);
10849
10850 Invalid = true;
10851 }
10852
10853 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10854 if (TemplateParameterListsAreEqual(TemplateParams,
10855 OldDecl->getTemplateParameters(),
10856 /*Complain=*/true,
10857 TPL_TemplateMatch))
10858 OldTemplateParams =
10859 OldDecl->getMostRecentDecl()->getTemplateParameters();
10860 else
10861 Invalid = true;
10862
10863 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10864 if (!Invalid &&
10865 !Context.hasSameType(OldTD->getUnderlyingType(),
10866 NewTD->getUnderlyingType())) {
10867 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10868 // but we can't reasonably accept it.
10869 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10870 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10871 if (OldTD->getLocation().isValid())
10872 Diag(OldTD->getLocation(), diag::note_previous_definition);
10873 Invalid = true;
10874 }
10875 }
10876 }
10877
10878 // Merge any previous default template arguments into our parameters,
10879 // and check the parameter list.
10880 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10881 TPC_TypeAliasTemplate))
10882 return nullptr;
10883
10884 TypeAliasTemplateDecl *NewDecl =
10885 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10886 Name.Identifier, TemplateParams,
10887 NewTD);
10888 NewTD->setDescribedAliasTemplate(NewDecl);
10889
10890 NewDecl->setAccess(AS);
10891
10892 if (Invalid)
10893 NewDecl->setInvalidDecl();
10894 else if (OldDecl) {
10895 NewDecl->setPreviousDecl(OldDecl);
10896 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10897 }
10898
10899 NewND = NewDecl;
10900 } else {
10901 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10902 setTagNameForLinkagePurposes(TD, NewTD);
10903 handleTagNumbering(TD, S);
10904 }
10905 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10906 NewND = NewTD;
10907 }
10908
10909 PushOnScopeChains(NewND, S);
10910 ActOnDocumentableDecl(NewND);
10911 return NewND;
10912}
10913
10914Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10915 SourceLocation AliasLoc,
10916 IdentifierInfo *Alias, CXXScopeSpec &SS,
10917 SourceLocation IdentLoc,
10918 IdentifierInfo *Ident) {
10919
10920 // Lookup the namespace name.
10921 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10922 LookupParsedName(R, S, &SS);
10923
10924 if (R.isAmbiguous())
10925 return nullptr;
10926
10927 if (R.empty()) {
10928 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10929 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10930 return nullptr;
10931 }
10932 }
10933 assert(!R.isAmbiguous() && !R.empty())((!R.isAmbiguous() && !R.empty()) ? static_cast<void
> (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 10933, __PRETTY_FUNCTION__))
;
10934 NamedDecl *ND = R.getRepresentativeDecl();
10935
10936 // Check if we have a previous declaration with the same name.
10937 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10938 ForVisibleRedeclaration);
10939 LookupName(PrevR, S);
10940
10941 // Check we're not shadowing a template parameter.
10942 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10943 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10944 PrevR.clear();
10945 }
10946
10947 // Filter out any other lookup result from an enclosing scope.
10948 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10949 /*AllowInlineNamespace*/false);
10950
10951 // Find the previous declaration and check that we can redeclare it.
10952 NamespaceAliasDecl *Prev = nullptr;
10953 if (PrevR.isSingleResult()) {
10954 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10955 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10956 // We already have an alias with the same name that points to the same
10957 // namespace; check that it matches.
10958 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10959 Prev = AD;
10960 } else if (isVisible(PrevDecl)) {
10961 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10962 << Alias;
10963 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10964 << AD->getNamespace();
10965 return nullptr;
10966 }
10967 } else if (isVisible(PrevDecl)) {
10968 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10969 ? diag::err_redefinition
10970 : diag::err_redefinition_different_kind;
10971 Diag(AliasLoc, DiagID) << Alias;
10972 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10973 return nullptr;
10974 }
10975 }
10976
10977 // The use of a nested name specifier may trigger deprecation warnings.
10978 DiagnoseUseOfDecl(ND, IdentLoc);
10979
10980 NamespaceAliasDecl *AliasDecl =
10981 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10982 Alias, SS.getWithLocInContext(Context),
10983 IdentLoc, ND);
10984 if (Prev)
10985 AliasDecl->setPreviousDecl(Prev);
10986
10987 PushOnScopeChains(AliasDecl, S);
10988 return AliasDecl;
10989}
10990
10991namespace {
10992struct SpecialMemberExceptionSpecInfo
10993 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10994 SourceLocation Loc;
10995 Sema::ImplicitExceptionSpecification ExceptSpec;
10996
10997 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10998 Sema::CXXSpecialMember CSM,
10999 Sema::InheritedConstructorInfo *ICI,
11000 SourceLocation Loc)
11001 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
11002
11003 bool visitBase(CXXBaseSpecifier *Base);
11004 bool visitField(FieldDecl *FD);
11005
11006 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
11007 unsigned Quals);
11008
11009 void visitSubobjectCall(Subobject Subobj,
11010 Sema::SpecialMemberOverloadResult SMOR);
11011};
11012}
11013
11014bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
11015 auto *RT = Base->getType()->getAs<RecordType>();
11016 if (!RT)
11017 return false;
11018
11019 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
11020 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
11021 if (auto *BaseCtor = SMOR.getMethod()) {
11022 visitSubobjectCall(Base, BaseCtor);
11023 return false;
11024 }
11025
11026 visitClassSubobject(BaseClass, Base, 0);
11027 return false;
11028}
11029
11030bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
11031 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
11032 Expr *E = FD->getInClassInitializer();
11033 if (!E)
11034 // FIXME: It's a little wasteful to build and throw away a
11035 // CXXDefaultInitExpr here.
11036 // FIXME: We should have a single context note pointing at Loc, and
11037 // this location should be MD->getLocation() instead, since that's
11038 // the location where we actually use the default init expression.
11039 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
11040 if (E)
11041 ExceptSpec.CalledExpr(E);
11042 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
11043 ->getAs<RecordType>()) {
11044 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
11045 FD->getType().getCVRQualifiers());
11046 }
11047 return false;
11048}
11049
11050void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
11051 Subobject Subobj,
11052 unsigned Quals) {
11053 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
11054 bool IsMutable = Field && Field->isMutable();
11055 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
11056}
11057
11058void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
11059 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
11060 // Note, if lookup fails, it doesn't matter what exception specification we
11061 // choose because the special member will be deleted.
11062 if (CXXMethodDecl *MD = SMOR.getMethod())
11063 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
11064}
11065
11066namespace {
11067/// RAII object to register a special member as being currently declared.
11068struct ComputingExceptionSpec {
11069 Sema &S;
11070
11071 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
11072 : S(S) {
11073 Sema::CodeSynthesisContext Ctx;
11074 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
11075 Ctx.PointOfInstantiation = Loc;
11076 Ctx.Entity = MD;
11077 S.pushCodeSynthesisContext(Ctx);
11078 }
11079 ~ComputingExceptionSpec() {
11080 S.popCodeSynthesisContext();
11081 }
11082};
11083}
11084
11085bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
11086 llvm::APSInt Result;
11087 ExprResult Converted = CheckConvertedConstantExpression(
11088 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
11089 ExplicitSpec.setExpr(Converted.get());
11090 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
11091 ExplicitSpec.setKind(Result.getBoolValue()
11092 ? ExplicitSpecKind::ResolvedTrue
11093 : ExplicitSpecKind::ResolvedFalse);
11094 return true;
11095 }
11096 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
11097 return false;
11098}
11099
11100ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
11101 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
11102 if (!ExplicitExpr->isTypeDependent())
11103 tryResolveExplicitSpecifier(ES);
11104 return ES;
11105}
11106
11107static Sema::ImplicitExceptionSpecification
11108ComputeDefaultedSpecialMemberExceptionSpec(
11109 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
11110 Sema::InheritedConstructorInfo *ICI) {
11111 ComputingExceptionSpec CES(S, MD, Loc);
11112
11113 CXXRecordDecl *ClassDecl = MD->getParent();
11114
11115 // C++ [except.spec]p14:
11116 // An implicitly declared special member function (Clause 12) shall have an
11117 // exception-specification. [...]
11118 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
11119 if (ClassDecl->isInvalidDecl())
11120 return Info.ExceptSpec;
11121
11122 // FIXME: If this diagnostic fires, we're probably missing a check for
11123 // attempting to resolve an exception specification before it's known
11124 // at a higher level.
11125 if (S.RequireCompleteType(MD->getLocation(),
11126 S.Context.getRecordType(ClassDecl),
11127 diag::err_exception_spec_incomplete_type))
11128 return Info.ExceptSpec;
11129
11130 // C++1z [except.spec]p7:
11131 // [Look for exceptions thrown by] a constructor selected [...] to
11132 // initialize a potentially constructed subobject,
11133 // C++1z [except.spec]p8:
11134 // The exception specification for an implicitly-declared destructor, or a
11135 // destructor without a noexcept-specifier, is potentially-throwing if and
11136 // only if any of the destructors for any of its potentially constructed
11137 // subojects is potentially throwing.
11138 // FIXME: We respect the first rule but ignore the "potentially constructed"
11139 // in the second rule to resolve a core issue (no number yet) that would have
11140 // us reject:
11141 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
11142 // struct B : A {};
11143 // struct C : B { void f(); };
11144 // ... due to giving B::~B() a non-throwing exception specification.
11145 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
11146 : Info.VisitAllBases);
11147
11148 return Info.ExceptSpec;
11149}
11150
11151namespace {
11152/// RAII object to register a special member as being currently declared.
11153struct DeclaringSpecialMember {
11154 Sema &S;
11155 Sema::SpecialMemberDecl D;
11156 Sema::ContextRAII SavedContext;
11157 bool WasAlreadyBeingDeclared;
11158
11159 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
11160 : S(S), D(RD, CSM), SavedContext(S, RD) {
11161 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
11162 if (WasAlreadyBeingDeclared)
11163 // This almost never happens, but if it does, ensure that our cache
11164 // doesn't contain a stale result.
11165 S.SpecialMemberCache.clear();
11166 else {
11167 // Register a note to be produced if we encounter an error while
11168 // declaring the special member.
11169 Sema::CodeSynthesisContext Ctx;
11170 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
11171 // FIXME: We don't have a location to use here. Using the class's
11172 // location maintains the fiction that we declare all special members
11173 // with the class, but (1) it's not clear that lying about that helps our
11174 // users understand what's going on, and (2) there may be outer contexts
11175 // on the stack (some of which are relevant) and printing them exposes
11176 // our lies.
11177 Ctx.PointOfInstantiation = RD->getLocation();
11178 Ctx.Entity = RD;
11179 Ctx.SpecialMember = CSM;
11180 S.pushCodeSynthesisContext(Ctx);
11181 }
11182 }
11183 ~DeclaringSpecialMember() {
11184 if (!WasAlreadyBeingDeclared) {
11185 S.SpecialMembersBeingDeclared.erase(D);
11186 S.popCodeSynthesisContext();
11187 }
11188 }
11189
11190 /// Are we already trying to declare this special member?
11191 bool isAlreadyBeingDeclared() const {
11192 return WasAlreadyBeingDeclared;
11193 }
11194};
11195}
11196
11197void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
11198 // Look up any existing declarations, but don't trigger declaration of all
11199 // implicit special members with this name.
11200 DeclarationName Name = FD->getDeclName();
11201 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
11202 ForExternalRedeclaration);
11203 for (auto *D : FD->getParent()->lookup(Name))
11204 if (auto *Acceptable = R.getAcceptableDecl(D))
11205 R.addDecl(Acceptable);
11206 R.resolveKind();
11207 R.suppressDiagnostics();
11208
11209 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11210}
11211
11212void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11213 QualType ResultTy,
11214 ArrayRef<QualType> Args) {
11215 // Build an exception specification pointing back at this constructor.
11216 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11217
11218 if (getLangOpts().OpenCLCPlusPlus) {
11219 // OpenCL: Implicitly defaulted special member are of the generic address
11220 // space.
11221 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11222 }
11223
11224 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11225 SpecialMem->setType(QT);
11226}
11227
11228CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11229 CXXRecordDecl *ClassDecl) {
11230 // C++ [class.ctor]p5:
11231 // A default constructor for a class X is a constructor of class X
11232 // that can be called without an argument. If there is no
11233 // user-declared constructor for class X, a default constructor is
11234 // implicitly declared. An implicitly-declared default constructor
11235 // is an inline public member of its class.
11236 assert(ClassDecl->needsImplicitDefaultConstructor() &&((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11237, __PRETTY_FUNCTION__))
11237 "Should not build implicit default constructor!")((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11237, __PRETTY_FUNCTION__))
;
11238
11239 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11240 if (DSM.isAlreadyBeingDeclared())
11241 return nullptr;
11242
11243 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11244 CXXDefaultConstructor,
11245 false);
11246
11247 // Create the actual constructor declaration.
11248 CanQualType ClassType
11249 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11250 SourceLocation ClassLoc = ClassDecl->getLocation();
11251 DeclarationName Name
11252 = Context.DeclarationNames.getCXXConstructorName(ClassType);
11253 DeclarationNameInfo NameInfo(Name, ClassLoc);
11254 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11255 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11256 /*TInfo=*/nullptr, ExplicitSpecifier(),
11257 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11258 Constexpr ? CSK_constexpr : CSK_unspecified);
11259 DefaultCon->setAccess(AS_public);
11260 DefaultCon->setDefaulted();
11261
11262 if (getLangOpts().CUDA) {
11263 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11264 DefaultCon,
11265 /* ConstRHS */ false,
11266 /* Diagnose */ false);
11267 }
11268
11269 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11270
11271 // We don't need to use SpecialMemberIsTrivial here; triviality for default
11272 // constructors is easy to compute.
11273 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11274
11275 // Note that we have declared this constructor.
11276 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11277
11278 Scope *S = getScopeForContext(ClassDecl);
11279 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11280
11281 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11282 SetDeclDeleted(DefaultCon, ClassLoc);
11283
11284 if (S)
11285 PushOnScopeChains(DefaultCon, S, false);
11286 ClassDecl->addDecl(DefaultCon);
11287
11288 return DefaultCon;
11289}
11290
11291void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11292 CXXConstructorDecl *Constructor) {
11293 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11296, __PRETTY_FUNCTION__))
11294 !Constructor->doesThisDeclarationHaveABody() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11296, __PRETTY_FUNCTION__))
11295 !Constructor->isDeleted()) &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11296, __PRETTY_FUNCTION__))
11296 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(((Constructor->isDefaulted() && Constructor->isDefaultConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11296, __PRETTY_FUNCTION__))
;
11297 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11298 return;
11299
11300 CXXRecordDecl *ClassDecl = Constructor->getParent();
11301 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")((ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11301, __PRETTY_FUNCTION__))
;
11302
11303 SynthesizedFunctionScope Scope(*this, Constructor);
11304
11305 // The exception specification is needed because we are defining the
11306 // function.
11307 ResolveExceptionSpec(CurrentLocation,
11308 Constructor->getType()->castAs<FunctionProtoType>());
11309 MarkVTableUsed(CurrentLocation, ClassDecl);
11310
11311 // Add a context note for diagnostics produced after this point.
11312 Scope.addContextNote(CurrentLocation);
11313
11314 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11315 Constructor->setInvalidDecl();
11316 return;
11317 }
11318
11319 SourceLocation Loc = Constructor->getEndLoc().isValid()
11320 ? Constructor->getEndLoc()
11321 : Constructor->getLocation();
11322 Constructor->setBody(new (Context) CompoundStmt(Loc));
11323 Constructor->markUsed(Context);
11324
11325 if (ASTMutationListener *L = getASTMutationListener()) {
11326 L->CompletedImplicitDefinition(Constructor);
11327 }
11328
11329 DiagnoseUninitializedFields(*this, Constructor);
11330}
11331
11332void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11333 // Perform any delayed checks on exception specifications.
11334 CheckDelayedMemberExceptionSpecs();
11335}
11336
11337/// Find or create the fake constructor we synthesize to model constructing an
11338/// object of a derived class via a constructor of a base class.
11339CXXConstructorDecl *
11340Sema::findInheritingConstructor(SourceLocation Loc,
11341 CXXConstructorDecl *BaseCtor,
11342 ConstructorUsingShadowDecl *Shadow) {
11343 CXXRecordDecl *Derived = Shadow->getParent();
11344 SourceLocation UsingLoc = Shadow->getLocation();
11345
11346 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11347 // For now we use the name of the base class constructor as a member of the
11348 // derived class to indicate a (fake) inherited constructor name.
11349 DeclarationName Name = BaseCtor->getDeclName();
11350
11351 // Check to see if we already have a fake constructor for this inherited
11352 // constructor call.
11353 for (NamedDecl *Ctor : Derived->lookup(Name))
11354 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11355 ->getInheritedConstructor()
11356 .getConstructor(),
11357 BaseCtor))
11358 return cast<CXXConstructorDecl>(Ctor);
11359
11360 DeclarationNameInfo NameInfo(Name, UsingLoc);
11361 TypeSourceInfo *TInfo =
11362 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11363 FunctionProtoTypeLoc ProtoLoc =
11364 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11365
11366 // Check the inherited constructor is valid and find the list of base classes
11367 // from which it was inherited.
11368 InheritedConstructorInfo ICI(*this, Loc, Shadow);
11369
11370 bool Constexpr =
11371 BaseCtor->isConstexpr() &&
11372 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11373 false, BaseCtor, &ICI);
11374
11375 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11376 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11377 BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
11378 /*isImplicitlyDeclared=*/true,
11379 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11380 InheritedConstructor(Shadow, BaseCtor));
11381 if (Shadow->isInvalidDecl())
11382 DerivedCtor->setInvalidDecl();
11383
11384 // Build an unevaluated exception specification for this fake constructor.
11385 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11386 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11387 EPI.ExceptionSpec.Type = EST_Unevaluated;
11388 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11389 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11390 FPT->getParamTypes(), EPI));
11391
11392 // Build the parameter declarations.
11393 SmallVector<ParmVarDecl *, 16> ParamDecls;
11394 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11395 TypeSourceInfo *TInfo =
11396 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11397 ParmVarDecl *PD = ParmVarDecl::Create(
11398 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11399 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
11400 PD->setScopeInfo(0, I);
11401 PD->setImplicit();
11402 // Ensure attributes are propagated onto parameters (this matters for
11403 // format, pass_object_size, ...).
11404 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11405 ParamDecls.push_back(PD);
11406 ProtoLoc.setParam(I, PD);
11407 }
11408
11409 // Set up the new constructor.
11410 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")((!BaseCtor->isDeleted() && "should not use deleted constructor"
) ? static_cast<void> (0) : __assert_fail ("!BaseCtor->isDeleted() && \"should not use deleted constructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11410, __PRETTY_FUNCTION__))
;
11411 DerivedCtor->setAccess(BaseCtor->getAccess());
11412 DerivedCtor->setParams(ParamDecls);
11413 Derived->addDecl(DerivedCtor);
11414
11415 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11416 SetDeclDeleted(DerivedCtor, UsingLoc);
11417
11418 return DerivedCtor;
11419}
11420
11421void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11422 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11423 Ctor->getInheritedConstructor().getShadowDecl());
11424 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11425 /*Diagnose*/true);
11426}
11427
11428void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11429 CXXConstructorDecl *Constructor) {
11430 CXXRecordDecl *ClassDecl = Constructor->getParent();
11431 assert(Constructor->getInheritedConstructor() &&((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11433, __PRETTY_FUNCTION__))
11432 !Constructor->doesThisDeclarationHaveABody() &&((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11433, __PRETTY_FUNCTION__))
11433 !Constructor->isDeleted())((Constructor->getInheritedConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11433, __PRETTY_FUNCTION__))
;
11434 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11435 return;
11436
11437 // Initializations are performed "as if by a defaulted default constructor",
11438 // so enter the appropriate scope.
11439 SynthesizedFunctionScope Scope(*this, Constructor);
11440
11441 // The exception specification is needed because we are defining the
11442 // function.
11443 ResolveExceptionSpec(CurrentLocation,
11444 Constructor->getType()->castAs<FunctionProtoType>());
11445 MarkVTableUsed(CurrentLocation, ClassDecl);
11446
11447 // Add a context note for diagnostics produced after this point.
11448 Scope.addContextNote(CurrentLocation);
11449
11450 ConstructorUsingShadowDecl *Shadow =
11451 Constructor->getInheritedConstructor().getShadowDecl();
11452 CXXConstructorDecl *InheritedCtor =
11453 Constructor->getInheritedConstructor().getConstructor();
11454
11455 // [class.inhctor.init]p1:
11456 // initialization proceeds as if a defaulted default constructor is used to
11457 // initialize the D object and each base class subobject from which the
11458 // constructor was inherited
11459
11460 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11461 CXXRecordDecl *RD = Shadow->getParent();
11462 SourceLocation InitLoc = Shadow->getLocation();
11463
11464 // Build explicit initializers for all base classes from which the
11465 // constructor was inherited.
11466 SmallVector<CXXCtorInitializer*, 8> Inits;
11467 for (bool VBase : {false, true}) {
11468 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11469 if (B.isVirtual() != VBase)
11470 continue;
11471
11472 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11473 if (!BaseRD)
11474 continue;
11475
11476 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11477 if (!BaseCtor.first)
11478 continue;
11479
11480 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11481 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11482 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11483
11484 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11485 Inits.push_back(new (Context) CXXCtorInitializer(
11486 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11487 SourceLocation()));
11488 }
11489 }
11490
11491 // We now proceed as if for a defaulted default constructor, with the relevant
11492 // initializers replaced.
11493
11494 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11495 Constructor->setInvalidDecl();
11496 return;
11497 }
11498
11499 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11500 Constructor->markUsed(Context);
11501
11502 if (ASTMutationListener *L = getASTMutationListener()) {
11503 L->CompletedImplicitDefinition(Constructor);
11504 }
11505
11506 DiagnoseUninitializedFields(*this, Constructor);
11507}
11508
11509CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11510 // C++ [class.dtor]p2:
11511 // If a class has no user-declared destructor, a destructor is
11512 // declared implicitly. An implicitly-declared destructor is an
11513 // inline public member of its class.
11514 assert(ClassDecl->needsImplicitDestructor())((ClassDecl->needsImplicitDestructor()) ? static_cast<void
> (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11514, __PRETTY_FUNCTION__))
;
11515
11516 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11517 if (DSM.isAlreadyBeingDeclared())
11518 return nullptr;
11519
11520 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11521 CXXDestructor,
11522 false);
11523
11524 // Create the actual destructor declaration.
11525 CanQualType ClassType
11526 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11527 SourceLocation ClassLoc = ClassDecl->getLocation();
11528 DeclarationName Name
11529 = Context.DeclarationNames.getCXXDestructorName(ClassType);
11530 DeclarationNameInfo NameInfo(Name, ClassLoc);
11531 CXXDestructorDecl *Destructor =
11532 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11533 QualType(), nullptr, /*isInline=*/true,
11534 /*isImplicitlyDeclared=*/true,
11535 Constexpr ? CSK_constexpr : CSK_unspecified);
11536 Destructor->setAccess(AS_public);
11537 Destructor->setDefaulted();
11538
11539 if (getLangOpts().CUDA) {
11540 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11541 Destructor,
11542 /* ConstRHS */ false,
11543 /* Diagnose */ false);
11544 }
11545
11546 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11547
11548 // We don't need to use SpecialMemberIsTrivial here; triviality for
11549 // destructors is easy to compute.
11550 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11551 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11552 ClassDecl->hasTrivialDestructorForCall());
11553
11554 // Note that we have declared this destructor.
11555 ++getASTContext().NumImplicitDestructorsDeclared;
11556
11557 Scope *S = getScopeForContext(ClassDecl);
11558 CheckImplicitSpecialMemberDeclaration(S, Destructor);
11559
11560 // We can't check whether an implicit destructor is deleted before we complete
11561 // the definition of the class, because its validity depends on the alignment
11562 // of the class. We'll check this from ActOnFields once the class is complete.
11563 if (ClassDecl->isCompleteDefinition() &&
11564 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11565 SetDeclDeleted(Destructor, ClassLoc);
11566
11567 // Introduce this destructor into its scope.
11568 if (S)
11569 PushOnScopeChains(Destructor, S, false);
11570 ClassDecl->addDecl(Destructor);
11571
11572 return Destructor;
11573}
11574
11575void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11576 CXXDestructorDecl *Destructor) {
11577 assert((Destructor->isDefaulted() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11580, __PRETTY_FUNCTION__))
11578 !Destructor->doesThisDeclarationHaveABody() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11580, __PRETTY_FUNCTION__))
11579 !Destructor->isDeleted()) &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11580, __PRETTY_FUNCTION__))
11580 "DefineImplicitDestructor - call it for implicit default dtor")(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody
() && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11580, __PRETTY_FUNCTION__))
;
11581 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11582 return;
11583
11584 CXXRecordDecl *ClassDecl = Destructor->getParent();
11585 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")((ClassDecl && "DefineImplicitDestructor - invalid destructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11585, __PRETTY_FUNCTION__))
;
11586
11587 SynthesizedFunctionScope Scope(*this, Destructor);
11588
11589 // The exception specification is needed because we are defining the
11590 // function.
11591 ResolveExceptionSpec(CurrentLocation,
11592 Destructor->getType()->castAs<FunctionProtoType>());
11593 MarkVTableUsed(CurrentLocation, ClassDecl);
11594
11595 // Add a context note for diagnostics produced after this point.
11596 Scope.addContextNote(CurrentLocation);
11597
11598 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11599 Destructor->getParent());
11600
11601 if (CheckDestructor(Destructor)) {
11602 Destructor->setInvalidDecl();
11603 return;
11604 }
11605
11606 SourceLocation Loc = Destructor->getEndLoc().isValid()
11607 ? Destructor->getEndLoc()
11608 : Destructor->getLocation();
11609 Destructor->setBody(new (Context) CompoundStmt(Loc));
11610 Destructor->markUsed(Context);
11611
11612 if (ASTMutationListener *L = getASTMutationListener()) {
11613 L->CompletedImplicitDefinition(Destructor);
11614 }
11615}
11616
11617/// Perform any semantic analysis which needs to be delayed until all
11618/// pending class member declarations have been parsed.
11619void Sema::ActOnFinishCXXMemberDecls() {
11620 // If the context is an invalid C++ class, just suppress these checks.
11621 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11622 if (Record->isInvalidDecl()) {
11623 DelayedOverridingExceptionSpecChecks.clear();
11624 DelayedEquivalentExceptionSpecChecks.clear();
11625 return;
11626 }
11627 checkForMultipleExportedDefaultConstructors(*this, Record);
11628 }
11629}
11630
11631void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11632 referenceDLLExportedClassMethods();
11633
11634 if (!DelayedDllExportMemberFunctions.empty()) {
11635 SmallVector<CXXMethodDecl*, 4> WorkList;
11636 std::swap(DelayedDllExportMemberFunctions, WorkList);
11637 for (CXXMethodDecl *M : WorkList) {
11638 DefineImplicitSpecialMember(*this, M, M->getLocation());
11639
11640 // Pass the method to the consumer to get emitted. This is not necessary
11641 // for explicit instantiation definitions, as they will get emitted
11642 // anyway.
11643 if (M->getParent()->getTemplateSpecializationKind() !=
11644 TSK_ExplicitInstantiationDefinition)
11645 ActOnFinishInlineFunctionDef(M);
11646 }
11647 }
11648}
11649
11650void Sema::referenceDLLExportedClassMethods() {
11651 if (!DelayedDllExportClasses.empty()) {
11652 // Calling ReferenceDllExportedMembers might cause the current function to
11653 // be called again, so use a local copy of DelayedDllExportClasses.
11654 SmallVector<CXXRecordDecl *, 4> WorkList;
11655 std::swap(DelayedDllExportClasses, WorkList);
11656 for (CXXRecordDecl *Class : WorkList)
11657 ReferenceDllExportedMembers(*this, Class);
11658 }
11659}
11660
11661void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11662 assert(getLangOpts().CPlusPlus11 &&((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11663, __PRETTY_FUNCTION__))
11663 "adjusting dtor exception specs was introduced in c++11")((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11663, __PRETTY_FUNCTION__))
;
11664
11665 if (Destructor->isDependentContext())
11666 return;
11667
11668 // C++11 [class.dtor]p3:
11669 // A declaration of a destructor that does not have an exception-
11670 // specification is implicitly considered to have the same exception-
11671 // specification as an implicit declaration.
11672 const FunctionProtoType *DtorType = Destructor->getType()->
11673 getAs<FunctionProtoType>();
11674 if (DtorType->hasExceptionSpec())
11675 return;
11676
11677 // Replace the destructor's type, building off the existing one. Fortunately,
11678 // the only thing of interest in the destructor type is its extended info.
11679 // The return and arguments are fixed.
11680 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11681 EPI.ExceptionSpec.Type = EST_Unevaluated;
11682 EPI.ExceptionSpec.SourceDecl = Destructor;
11683 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11684
11685 // FIXME: If the destructor has a body that could throw, and the newly created
11686 // spec doesn't allow exceptions, we should emit a warning, because this
11687 // change in behavior can break conforming C++03 programs at runtime.
11688 // However, we don't have a body or an exception specification yet, so it
11689 // needs to be done somewhere else.
11690}
11691
11692namespace {
11693/// An abstract base class for all helper classes used in building the
11694// copy/move operators. These classes serve as factory functions and help us
11695// avoid using the same Expr* in the AST twice.
11696class ExprBuilder {
11697 ExprBuilder(const ExprBuilder&) = delete;
11698 ExprBuilder &operator=(const ExprBuilder&) = delete;
11699
11700protected:
11701 static Expr *assertNotNull(Expr *E) {
11702 assert(E && "Expression construction must not fail.")((E && "Expression construction must not fail.") ? static_cast
<void> (0) : __assert_fail ("E && \"Expression construction must not fail.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11702, __PRETTY_FUNCTION__))
;
11703 return E;
11704 }
11705
11706public:
11707 ExprBuilder() {}
11708 virtual ~ExprBuilder() {}
11709
11710 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11711};
11712
11713class RefBuilder: public ExprBuilder {
11714 VarDecl *Var;
11715 QualType VarType;
11716
11717public:
11718 Expr *build(Sema &S, SourceLocation Loc) const override {
11719 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11720 }
11721
11722 RefBuilder(VarDecl *Var, QualType VarType)
11723 : Var(Var), VarType(VarType) {}
11724};
11725
11726class ThisBuilder: public ExprBuilder {
11727public:
11728 Expr *build(Sema &S, SourceLocation Loc) const override {
11729 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11730 }
11731};
11732
11733class CastBuilder: public ExprBuilder {
11734 const ExprBuilder &Builder;
11735 QualType Type;
11736 ExprValueKind Kind;
11737 const CXXCastPath &Path;
11738
11739public:
11740 Expr *build(Sema &S, SourceLocation Loc) const override {
11741 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11742 CK_UncheckedDerivedToBase, Kind,
11743 &Path).get());
11744 }
11745
11746 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11747 const CXXCastPath &Path)
11748 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11749};
11750
11751class DerefBuilder: public ExprBuilder {
11752 const ExprBuilder &Builder;
11753
11754public:
11755 Expr *build(Sema &S, SourceLocation Loc) const override {
11756 return assertNotNull(
11757 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11758 }
11759
11760 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11761};
11762
11763class MemberBuilder: public ExprBuilder {
11764 const ExprBuilder &Builder;
11765 QualType Type;
11766 CXXScopeSpec SS;
11767 bool IsArrow;
11768 LookupResult &MemberLookup;
11769
11770public:
11771 Expr *build(Sema &S, SourceLocation Loc) const override {
11772 return assertNotNull(S.BuildMemberReferenceExpr(
11773 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11774 nullptr, MemberLookup, nullptr, nullptr).get());
11775 }
11776
11777 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11778 LookupResult &MemberLookup)
11779 : Builder(Builder), Type(Type), IsArrow(IsArrow),
11780 MemberLookup(MemberLookup) {}
11781};
11782
11783class MoveCastBuilder: public ExprBuilder {
11784 const ExprBuilder &Builder;
11785
11786public:
11787 Expr *build(Sema &S, SourceLocation Loc) const override {
11788 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11789 }
11790
11791 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11792};
11793
11794class LvalueConvBuilder: public ExprBuilder {
11795 const ExprBuilder &Builder;
11796
11797public:
11798 Expr *build(Sema &S, SourceLocation Loc) const override {
11799 return assertNotNull(
11800 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11801 }
11802
11803 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11804};
11805
11806class SubscriptBuilder: public ExprBuilder {
11807 const ExprBuilder &Base;
11808 const ExprBuilder &Index;
11809
11810public:
11811 Expr *build(Sema &S, SourceLocation Loc) const override {
11812 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11813 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11814 }
11815
11816 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11817 : Base(Base), Index(Index) {}
11818};
11819
11820} // end anonymous namespace
11821
11822/// When generating a defaulted copy or move assignment operator, if a field
11823/// should be copied with __builtin_memcpy rather than via explicit assignments,
11824/// do so. This optimization only applies for arrays of scalars, and for arrays
11825/// of class type where the selected copy/move-assignment operator is trivial.
11826static StmtResult
11827buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11828 const ExprBuilder &ToB, const ExprBuilder &FromB) {
11829 // Compute the size of the memory buffer to be copied.
11830 QualType SizeType = S.Context.getSizeType();
11831 llvm::APInt Size(S.Context.getTypeSize(SizeType),
11832 S.Context.getTypeSizeInChars(T).getQuantity());
11833
11834 // Take the address of the field references for "from" and "to". We
11835 // directly construct UnaryOperators here because semantic analysis
11836 // does not permit us to take the address of an xvalue.
11837 Expr *From = FromB.build(S, Loc);
11838 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11839 S.Context.getPointerType(From->getType()),
11840 VK_RValue, OK_Ordinary, Loc, false);
11841 Expr *To = ToB.build(S, Loc);
11842 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11843 S.Context.getPointerType(To->getType()),
11844 VK_RValue, OK_Ordinary, Loc, false);
11845
11846 const Type *E = T->getBaseElementTypeUnsafe();
11847 bool NeedsCollectableMemCpy =
11848 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11849
11850 // Create a reference to the __builtin_objc_memmove_collectable function
11851 StringRef MemCpyName = NeedsCollectableMemCpy ?
11852 "__builtin_objc_memmove_collectable" :
11853 "__builtin_memcpy";
11854 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11855 Sema::LookupOrdinaryName);
11856 S.LookupName(R, S.TUScope, true);
11857
11858 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11859 if (!MemCpy)
11860 // Something went horribly wrong earlier, and we will have complained
11861 // about it.
11862 return StmtError();
11863
11864 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11865 VK_RValue, Loc, nullptr);
11866 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")((MemCpyRef.isUsable() && "Builtin reference cannot fail"
) ? static_cast<void> (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11866, __PRETTY_FUNCTION__))
;
11867
11868 Expr *CallArgs[] = {
11869 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11870 };
11871 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11872 Loc, CallArgs, Loc);
11873
11874 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")((!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"
) ? static_cast<void> (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 11874, __PRETTY_FUNCTION__))
;
11875 return Call.getAs<Stmt>();
11876}
11877
11878/// Builds a statement that copies/moves the given entity from \p From to
11879/// \c To.
11880///
11881/// This routine is used to copy/move the members of a class with an
11882/// implicitly-declared copy/move assignment operator. When the entities being
11883/// copied are arrays, this routine builds for loops to copy them.
11884///
11885/// \param S The Sema object used for type-checking.
11886///
11887/// \param Loc The location where the implicit copy/move is being generated.
11888///
11889/// \param T The type of the expressions being copied/moved. Both expressions
11890/// must have this type.
11891///
11892/// \param To The expression we are copying/moving to.
11893///
11894/// \param From The expression we are copying/moving from.
11895///
11896/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11897/// Otherwise, it's a non-static member subobject.
11898///
11899/// \param Copying Whether we're copying or moving.
11900///
11901/// \param Depth Internal parameter recording the depth of the recursion.
11902///
11903/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11904/// if a memcpy should be used instead.
11905static StmtResult
11906buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11907 const ExprBuilder &To, const ExprBuilder &From,
11908 bool CopyingBaseSubobject, bool Copying,
11909 unsigned Depth = 0) {
11910 // C++11 [class.copy]p28:
11911 // Each subobject is assigned in the manner appropriate to its type:
11912 //
11913 // - if the subobject is of class type, as if by a call to operator= with
11914 // the subobject as the object expression and the corresponding
11915 // subobject of x as a single function argument (as if by explicit
11916 // qualification; that is, ignoring any possible virtual overriding
11917 // functions in more derived classes);
11918 //
11919 // C++03 [class.copy]p13:
11920 // - if the subobject is of class type, the copy assignment operator for
11921 // the class is used (as if by explicit qualification; that is,
11922 // ignoring any possible virtual overriding functions in more derived
11923 // classes);
11924 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11925 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11926
11927 // Look for operator=.
11928 DeclarationName Name
11929 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11930 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11931 S.LookupQualifiedName(OpLookup, ClassDecl, false);
11932
11933 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11934 // operator.
11935 if (!S.getLangOpts().CPlusPlus11) {
11936 LookupResult::Filter F = OpLookup.makeFilter();
11937 while (F.hasNext()) {
11938 NamedDecl *D = F.next();
11939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11940 if (Method->isCopyAssignmentOperator() ||
11941 (!Copying && Method->isMoveAssignmentOperator()))
11942 continue;
11943
11944 F.erase();
11945 }
11946 F.done();
11947 }
11948
11949 // Suppress the protected check (C++ [class.protected]) for each of the
11950 // assignment operators we found. This strange dance is required when
11951 // we're assigning via a base classes's copy-assignment operator. To
11952 // ensure that we're getting the right base class subobject (without
11953 // ambiguities), we need to cast "this" to that subobject type; to
11954 // ensure that we don't go through the virtual call mechanism, we need
11955 // to qualify the operator= name with the base class (see below). However,
11956 // this means that if the base class has a protected copy assignment
11957 // operator, the protected member access check will fail. So, we
11958 // rewrite "protected" access to "public" access in this case, since we
11959 // know by construction that we're calling from a derived class.
11960 if (CopyingBaseSubobject) {
11961 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11962 L != LEnd; ++L) {
11963 if (L.getAccess() == AS_protected)
11964 L.setAccess(AS_public);
11965 }
11966 }
11967
11968 // Create the nested-name-specifier that will be used to qualify the
11969 // reference to operator=; this is required to suppress the virtual
11970 // call mechanism.
11971 CXXScopeSpec SS;
11972 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11973 SS.MakeTrivial(S.Context,
11974 NestedNameSpecifier::Create(S.Context, nullptr, false,
11975 CanonicalT),
11976 Loc);
11977
11978 // Create the reference to operator=.
11979 ExprResult OpEqualRef
11980 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
11981 SS, /*TemplateKWLoc=*/SourceLocation(),
11982 /*FirstQualifierInScope=*/nullptr,
11983 OpLookup,
11984 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11985 /*SuppressQualifierCheck=*/true);
11986 if (OpEqualRef.isInvalid())
11987 return StmtError();
11988
11989 // Build the call to the assignment operator.
11990
11991 Expr *FromInst = From.build(S, Loc);
11992 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11993 OpEqualRef.getAs<Expr>(),
11994 Loc, FromInst, Loc);
11995 if (Call.isInvalid())
11996 return StmtError();
11997
11998 // If we built a call to a trivial 'operator=' while copying an array,
11999 // bail out. We'll replace the whole shebang with a memcpy.
12000 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
12001 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
12002 return StmtResult((Stmt*)nullptr);
12003
12004 // Convert to an expression-statement, and clean up any produced
12005 // temporaries.
12006 return S.ActOnExprStmt(Call);
12007 }
12008
12009 // - if the subobject is of scalar type, the built-in assignment
12010 // operator is used.
12011 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
12012 if (!ArrayTy) {
12013 ExprResult Assignment = S.CreateBuiltinBinOp(
12014 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
12015 if (Assignment.isInvalid())
12016 return StmtError();
12017 return S.ActOnExprStmt(Assignment);
12018 }
12019
12020 // - if the subobject is an array, each element is assigned, in the
12021 // manner appropriate to the element type;
12022
12023 // Construct a loop over the array bounds, e.g.,
12024 //
12025 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
12026 //
12027 // that will copy each of the array elements.
12028 QualType SizeType = S.Context.getSizeType();
12029
12030 // Create the iteration variable.
12031 IdentifierInfo *IterationVarName = nullptr;
12032 {
12033 SmallString<8> Str;
12034 llvm::raw_svector_ostream OS(Str);
12035 OS << "__i" << Depth;
12036 IterationVarName = &S.Context.Idents.get(OS.str());
12037 }
12038 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
12039 IterationVarName, SizeType,
12040 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
12041 SC_None);
12042
12043 // Initialize the iteration variable to zero.
12044 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
12045 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
12046
12047 // Creates a reference to the iteration variable.
12048 RefBuilder IterationVarRef(IterationVar, SizeType);
12049 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
12050
12051 // Create the DeclStmt that holds the iteration variable.
12052 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
12053
12054 // Subscript the "from" and "to" expressions with the iteration variable.
12055 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
12056 MoveCastBuilder FromIndexMove(FromIndexCopy);
12057 const ExprBuilder *FromIndex;
12058 if (Copying)
12059 FromIndex = &FromIndexCopy;
12060 else
12061 FromIndex = &FromIndexMove;
12062
12063 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
12064
12065 // Build the copy/move for an individual element of the array.
12066 StmtResult Copy =
12067 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
12068 ToIndex, *FromIndex, CopyingBaseSubobject,
12069 Copying, Depth + 1);
12070 // Bail out if copying fails or if we determined that we should use memcpy.
12071 if (Copy.isInvalid() || !Copy.get())
12072 return Copy;
12073
12074 // Create the comparison against the array bound.
12075 llvm::APInt Upper
12076 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
12077 Expr *Comparison
12078 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
12079 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
12080 BO_NE, S.Context.BoolTy,
12081 VK_RValue, OK_Ordinary, Loc, FPOptions());
12082
12083 // Create the pre-increment of the iteration variable. We can determine
12084 // whether the increment will overflow based on the value of the array
12085 // bound.
12086 Expr *Increment = new (S.Context)
12087 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
12088 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
12089
12090 // Construct the loop that copies all elements of this array.
12091 return S.ActOnForStmt(
12092 Loc, Loc, InitStmt,
12093 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
12094 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
12095}
12096
12097static StmtResult
12098buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
12099 const ExprBuilder &To, const ExprBuilder &From,
12100 bool CopyingBaseSubobject, bool Copying) {
12101 // Maybe we should use a memcpy?
12102 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
12103 T.isTriviallyCopyableType(S.Context))
12104 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12105
12106 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
12107 CopyingBaseSubobject,
12108 Copying, 0));
12109
12110 // If we ended up picking a trivial assignment operator for an array of a
12111 // non-trivially-copyable class type, just emit a memcpy.
12112 if (!Result.isInvalid() && !Result.get())
12113 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12114
12115 return Result;
12116}
12117
12118CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
12119 // Note: The following rules are largely analoguous to the copy
12120 // constructor rules. Note that virtual bases are not taken into account
12121 // for determining the argument type of the operator. Note also that
12122 // operators taking an object instead of a reference are allowed.
12123 assert(ClassDecl->needsImplicitCopyAssignment())((ClassDecl->needsImplicitCopyAssignment()) ? static_cast<
void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12123, __PRETTY_FUNCTION__))
;
12124
12125 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
12126 if (DSM.isAlreadyBeingDeclared())
12127 return nullptr;
12128
12129 QualType ArgType = Context.getTypeDeclType(ClassDecl);
12130 if (Context.getLangOpts().OpenCLCPlusPlus)
12131 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12132 QualType RetType = Context.getLValueReferenceType(ArgType);
12133 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
12134 if (Const)
12135 ArgType = ArgType.withConst();
12136
12137 ArgType = Context.getLValueReferenceType(ArgType);
12138
12139 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12140 CXXCopyAssignment,
12141 Const);
12142
12143 // An implicitly-declared copy assignment operator is an inline public
12144 // member of its class.
12145 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12146 SourceLocation ClassLoc = ClassDecl->getLocation();
12147 DeclarationNameInfo NameInfo(Name, ClassLoc);
12148 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
12149 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12150 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12151 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12152 SourceLocation());
12153 CopyAssignment->setAccess(AS_public);
12154 CopyAssignment->setDefaulted();
12155 CopyAssignment->setImplicit();
12156
12157 if (getLangOpts().CUDA) {
12158 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
12159 CopyAssignment,
12160 /* ConstRHS */ Const,
12161 /* Diagnose */ false);
12162 }
12163
12164 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
12165
12166 // Add the parameter to the operator.
12167 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
12168 ClassLoc, ClassLoc,
12169 /*Id=*/nullptr, ArgType,
12170 /*TInfo=*/nullptr, SC_None,
12171 nullptr);
12172 CopyAssignment->setParams(FromParam);
12173
12174 CopyAssignment->setTrivial(
12175 ClassDecl->needsOverloadResolutionForCopyAssignment()
12176 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
12177 : ClassDecl->hasTrivialCopyAssignment());
12178
12179 // Note that we have added this copy-assignment operator.
12180 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
12181
12182 Scope *S = getScopeForContext(ClassDecl);
12183 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
12184
12185 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
12186 SetDeclDeleted(CopyAssignment, ClassLoc);
12187
12188 if (S)
12189 PushOnScopeChains(CopyAssignment, S, false);
12190 ClassDecl->addDecl(CopyAssignment);
12191
12192 return CopyAssignment;
12193}
12194
12195/// Diagnose an implicit copy operation for a class which is odr-used, but
12196/// which is deprecated because the class has a user-declared copy constructor,
12197/// copy assignment operator, or destructor.
12198static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
12199 assert(CopyOp->isImplicit())((CopyOp->isImplicit()) ? static_cast<void> (0) : __assert_fail
("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12199, __PRETTY_FUNCTION__))
;
12200
12201 CXXRecordDecl *RD = CopyOp->getParent();
12202 CXXMethodDecl *UserDeclaredOperation = nullptr;
12203
12204 // In Microsoft mode, assignment operations don't affect constructors and
12205 // vice versa.
12206 if (RD->hasUserDeclaredDestructor()) {
12207 UserDeclaredOperation = RD->getDestructor();
12208 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
12209 RD->hasUserDeclaredCopyConstructor() &&
12210 !S.getLangOpts().MSVCCompat) {
12211 // Find any user-declared copy constructor.
12212 for (auto *I : RD->ctors()) {
12213 if (I->isCopyConstructor()) {
12214 UserDeclaredOperation = I;
12215 break;
12216 }
12217 }
12218 assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail
("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12218, __PRETTY_FUNCTION__))
;
12219 } else if (isa<CXXConstructorDecl>(CopyOp) &&
12220 RD->hasUserDeclaredCopyAssignment() &&
12221 !S.getLangOpts().MSVCCompat) {
12222 // Find any user-declared move assignment operator.
12223 for (auto *I : RD->methods()) {
12224 if (I->isCopyAssignmentOperator()) {
12225 UserDeclaredOperation = I;
12226 break;
12227 }
12228 }
12229 assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail
("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12229, __PRETTY_FUNCTION__))
;
12230 }
12231
12232 if (UserDeclaredOperation) {
12233 S.Diag(UserDeclaredOperation->getLocation(),
12234 diag::warn_deprecated_copy_operation)
12235 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12236 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12237 }
12238}
12239
12240void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12241 CXXMethodDecl *CopyAssignOperator) {
12242 assert((CopyAssignOperator->isDefaulted() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12247, __PRETTY_FUNCTION__))
12243 CopyAssignOperator->isOverloadedOperator() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12247, __PRETTY_FUNCTION__))
12244 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12247, __PRETTY_FUNCTION__))
12245 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12247, __PRETTY_FUNCTION__))
12246 !CopyAssignOperator->isDeleted()) &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12247, __PRETTY_FUNCTION__))
12247 "DefineImplicitCopyAssignment called for wrong function")(((CopyAssignOperator->isDefaulted() && CopyAssignOperator
->isOverloadedOperator() && CopyAssignOperator->
getOverloadedOperator() == OO_Equal && !CopyAssignOperator
->doesThisDeclarationHaveABody() && !CopyAssignOperator
->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12247, __PRETTY_FUNCTION__))
;
12248 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12249 return;
12250
12251 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12252 if (ClassDecl->isInvalidDecl()) {
12253 CopyAssignOperator->setInvalidDecl();
12254 return;
12255 }
12256
12257 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12258
12259 // The exception specification is needed because we are defining the
12260 // function.
12261 ResolveExceptionSpec(CurrentLocation,
12262 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12263
12264 // Add a context note for diagnostics produced after this point.
12265 Scope.addContextNote(CurrentLocation);
12266
12267 // C++11 [class.copy]p18:
12268 // The [definition of an implicitly declared copy assignment operator] is
12269 // deprecated if the class has a user-declared copy constructor or a
12270 // user-declared destructor.
12271 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12272 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12273
12274 // C++0x [class.copy]p30:
12275 // The implicitly-defined or explicitly-defaulted copy assignment operator
12276 // for a non-union class X performs memberwise copy assignment of its
12277 // subobjects. The direct base classes of X are assigned first, in the
12278 // order of their declaration in the base-specifier-list, and then the
12279 // immediate non-static data members of X are assigned, in the order in
12280 // which they were declared in the class definition.
12281
12282 // The statements that form the synthesized function body.
12283 SmallVector<Stmt*, 8> Statements;
12284
12285 // The parameter for the "other" object, which we are copying from.
12286 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12287 Qualifiers OtherQuals = Other->getType().getQualifiers();
12288 QualType OtherRefType = Other->getType();
12289 if (const LValueReferenceType *OtherRef
12290 = OtherRefType->getAs<LValueReferenceType>()) {
12291 OtherRefType = OtherRef->getPointeeType();
12292 OtherQuals = OtherRefType.getQualifiers();
12293 }
12294
12295 // Our location for everything implicitly-generated.
12296 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12297 ? CopyAssignOperator->getEndLoc()
12298 : CopyAssignOperator->getLocation();
12299
12300 // Builds a DeclRefExpr for the "other" object.
12301 RefBuilder OtherRef(Other, OtherRefType);
12302
12303 // Builds the "this" pointer.
12304 ThisBuilder This;
12305
12306 // Assign base classes.
12307 bool Invalid = false;
12308 for (auto &Base : ClassDecl->bases()) {
12309 // Form the assignment:
12310 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12311 QualType BaseType = Base.getType().getUnqualifiedType();
12312 if (!BaseType->isRecordType()) {
12313 Invalid = true;
12314 continue;
12315 }
12316
12317 CXXCastPath BasePath;
12318 BasePath.push_back(&Base);
12319
12320 // Construct the "from" expression, which is an implicit cast to the
12321 // appropriately-qualified base type.
12322 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12323 VK_LValue, BasePath);
12324
12325 // Dereference "this".
12326 DerefBuilder DerefThis(This);
12327 CastBuilder To(DerefThis,
12328 Context.getQualifiedType(
12329 BaseType, CopyAssignOperator->getMethodQualifiers()),
12330 VK_LValue, BasePath);
12331
12332 // Build the copy.
12333 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12334 To, From,
12335 /*CopyingBaseSubobject=*/true,
12336 /*Copying=*/true);
12337 if (Copy.isInvalid()) {
12338 CopyAssignOperator->setInvalidDecl();
12339 return;
12340 }
12341
12342 // Success! Record the copy.
12343 Statements.push_back(Copy.getAs<Expr>());
12344 }
12345
12346 // Assign non-static members.
12347 for (auto *Field : ClassDecl->fields()) {
12348 // FIXME: We should form some kind of AST representation for the implied
12349 // memcpy in a union copy operation.
12350 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12351 continue;
12352
12353 if (Field->isInvalidDecl()) {
12354 Invalid = true;
12355 continue;
12356 }
12357
12358 // Check for members of reference type; we can't copy those.
12359 if (Field->getType()->isReferenceType()) {
12360 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12361 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12362 Diag(Field->getLocation(), diag::note_declared_at);
12363 Invalid = true;
12364 continue;
12365 }
12366
12367 // Check for members of const-qualified, non-class type.
12368 QualType BaseType = Context.getBaseElementType(Field->getType());
12369 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12370 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12371 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12372 Diag(Field->getLocation(), diag::note_declared_at);
12373 Invalid = true;
12374 continue;
12375 }
12376
12377 // Suppress assigning zero-width bitfields.
12378 if (Field->isZeroLengthBitField(Context))
12379 continue;
12380
12381 QualType FieldType = Field->getType().getNonReferenceType();
12382 if (FieldType->isIncompleteArrayType()) {
12383 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12384, __PRETTY_FUNCTION__))
12384 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12384, __PRETTY_FUNCTION__))
;
12385 continue;
12386 }
12387
12388 // Build references to the field in the object we're copying from and to.
12389 CXXScopeSpec SS; // Intentionally empty
12390 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12391 LookupMemberName);
12392 MemberLookup.addDecl(Field);
12393 MemberLookup.resolveKind();
12394
12395 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12396
12397 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12398
12399 // Build the copy of this field.
12400 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12401 To, From,
12402 /*CopyingBaseSubobject=*/false,
12403 /*Copying=*/true);
12404 if (Copy.isInvalid()) {
12405 CopyAssignOperator->setInvalidDecl();
12406 return;
12407 }
12408
12409 // Success! Record the copy.
12410 Statements.push_back(Copy.getAs<Stmt>());
12411 }
12412
12413 if (!Invalid) {
12414 // Add a "return *this;"
12415 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12416
12417 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12418 if (Return.isInvalid())
12419 Invalid = true;
12420 else
12421 Statements.push_back(Return.getAs<Stmt>());
12422 }
12423
12424 if (Invalid) {
12425 CopyAssignOperator->setInvalidDecl();
12426 return;
12427 }
12428
12429 StmtResult Body;
12430 {
12431 CompoundScopeRAII CompoundScope(*this);
12432 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12433 /*isStmtExpr=*/false);
12434 assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail"
) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12434, __PRETTY_FUNCTION__))
;
12435 }
12436 CopyAssignOperator->setBody(Body.getAs<Stmt>());
12437 CopyAssignOperator->markUsed(Context);
12438
12439 if (ASTMutationListener *L = getASTMutationListener()) {
12440 L->CompletedImplicitDefinition(CopyAssignOperator);
12441 }
12442}
12443
12444CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12445 assert(ClassDecl->needsImplicitMoveAssignment())((ClassDecl->needsImplicitMoveAssignment()) ? static_cast<
void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12445, __PRETTY_FUNCTION__))
;
12446
12447 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12448 if (DSM.isAlreadyBeingDeclared())
12449 return nullptr;
12450
12451 // Note: The following rules are largely analoguous to the move
12452 // constructor rules.
12453
12454 QualType ArgType = Context.getTypeDeclType(ClassDecl);
12455 if (Context.getLangOpts().OpenCLCPlusPlus)
12456 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12457 QualType RetType = Context.getLValueReferenceType(ArgType);
12458 ArgType = Context.getRValueReferenceType(ArgType);
12459
12460 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12461 CXXMoveAssignment,
12462 false);
12463
12464 // An implicitly-declared move assignment operator is an inline public
12465 // member of its class.
12466 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12467 SourceLocation ClassLoc = ClassDecl->getLocation();
12468 DeclarationNameInfo NameInfo(Name, ClassLoc);
12469 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12470 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12471 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12472 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12473 SourceLocation());
12474 MoveAssignment->setAccess(AS_public);
12475 MoveAssignment->setDefaulted();
12476 MoveAssignment->setImplicit();
12477
12478 if (getLangOpts().CUDA) {
12479 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12480 MoveAssignment,
12481 /* ConstRHS */ false,
12482 /* Diagnose */ false);
12483 }
12484
12485 // Build an exception specification pointing back at this member.
12486 FunctionProtoType::ExtProtoInfo EPI =
12487 getImplicitMethodEPI(*this, MoveAssignment);
12488 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12489
12490 // Add the parameter to the operator.
12491 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12492 ClassLoc, ClassLoc,
12493 /*Id=*/nullptr, ArgType,
12494 /*TInfo=*/nullptr, SC_None,
12495 nullptr);
12496 MoveAssignment->setParams(FromParam);
12497
12498 MoveAssignment->setTrivial(
12499 ClassDecl->needsOverloadResolutionForMoveAssignment()
12500 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12501 : ClassDecl->hasTrivialMoveAssignment());
12502
12503 // Note that we have added this copy-assignment operator.
12504 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12505
12506 Scope *S = getScopeForContext(ClassDecl);
12507 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12508
12509 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12510 ClassDecl->setImplicitMoveAssignmentIsDeleted();
12511 SetDeclDeleted(MoveAssignment, ClassLoc);
12512 }
12513
12514 if (S)
12515 PushOnScopeChains(MoveAssignment, S, false);
12516 ClassDecl->addDecl(MoveAssignment);
12517
12518 return MoveAssignment;
12519}
12520
12521/// Check if we're implicitly defining a move assignment operator for a class
12522/// with virtual bases. Such a move assignment might move-assign the virtual
12523/// base multiple times.
12524static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12525 SourceLocation CurrentLocation) {
12526 assert(!Class->isDependentContext() && "should not define dependent move")((!Class->isDependentContext() && "should not define dependent move"
) ? static_cast<void> (0) : __assert_fail ("!Class->isDependentContext() && \"should not define dependent move\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12526, __PRETTY_FUNCTION__))
;
12527
12528 // Only a virtual base could get implicitly move-assigned multiple times.
12529 // Only a non-trivial move assignment can observe this. We only want to
12530 // diagnose if we implicitly define an assignment operator that assigns
12531 // two base classes, both of which move-assign the same virtual base.
12532 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12533 Class->getNumBases() < 2)
12534 return;
12535
12536 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12537 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12538 VBaseMap VBases;
12539
12540 for (auto &BI : Class->bases()) {
12541 Worklist.push_back(&BI);
12542 while (!Worklist.empty()) {
12543 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12544 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12545
12546 // If the base has no non-trivial move assignment operators,
12547 // we don't care about moves from it.
12548 if (!Base->hasNonTrivialMoveAssignment())
12549 continue;
12550
12551 // If there's nothing virtual here, skip it.
12552 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12553 continue;
12554
12555 // If we're not actually going to call a move assignment for this base,
12556 // or the selected move assignment is trivial, skip it.
12557 Sema::SpecialMemberOverloadResult SMOR =
12558 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12559 /*ConstArg*/false, /*VolatileArg*/false,
12560 /*RValueThis*/true, /*ConstThis*/false,
12561 /*VolatileThis*/false);
12562 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12563 !SMOR.getMethod()->isMoveAssignmentOperator())
12564 continue;
12565
12566 if (BaseSpec->isVirtual()) {
12567 // We're going to move-assign this virtual base, and its move
12568 // assignment operator is not trivial. If this can happen for
12569 // multiple distinct direct bases of Class, diagnose it. (If it
12570 // only happens in one base, we'll diagnose it when synthesizing
12571 // that base class's move assignment operator.)
12572 CXXBaseSpecifier *&Existing =
12573 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12574 .first->second;
12575 if (Existing && Existing != &BI) {
12576 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12577 << Class << Base;
12578 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12579 << (Base->getCanonicalDecl() ==
12580 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12581 << Base << Existing->getType() << Existing->getSourceRange();
12582 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12583 << (Base->getCanonicalDecl() ==
12584 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12585 << Base << BI.getType() << BaseSpec->getSourceRange();
12586
12587 // Only diagnose each vbase once.
12588 Existing = nullptr;
12589 }
12590 } else {
12591 // Only walk over bases that have defaulted move assignment operators.
12592 // We assume that any user-provided move assignment operator handles
12593 // the multiple-moves-of-vbase case itself somehow.
12594 if (!SMOR.getMethod()->isDefaulted())
12595 continue;
12596
12597 // We're going to move the base classes of Base. Add them to the list.
12598 for (auto &BI : Base->bases())
12599 Worklist.push_back(&BI);
12600 }
12601 }
12602 }
12603}
12604
12605void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12606 CXXMethodDecl *MoveAssignOperator) {
12607 assert((MoveAssignOperator->isDefaulted() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12612, __PRETTY_FUNCTION__))
12608 MoveAssignOperator->isOverloadedOperator() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12612, __PRETTY_FUNCTION__))
12609 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12612, __PRETTY_FUNCTION__))
12610 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12612, __PRETTY_FUNCTION__))
12611 !MoveAssignOperator->isDeleted()) &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12612, __PRETTY_FUNCTION__))
12612 "DefineImplicitMoveAssignment called for wrong function")(((MoveAssignOperator->isDefaulted() && MoveAssignOperator
->isOverloadedOperator() && MoveAssignOperator->
getOverloadedOperator() == OO_Equal && !MoveAssignOperator
->doesThisDeclarationHaveABody() && !MoveAssignOperator
->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12612, __PRETTY_FUNCTION__))
;
12613 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12614 return;
12615
12616 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12617 if (ClassDecl->isInvalidDecl()) {
12618 MoveAssignOperator->setInvalidDecl();
12619 return;
12620 }
12621
12622 // C++0x [class.copy]p28:
12623 // The implicitly-defined or move assignment operator for a non-union class
12624 // X performs memberwise move assignment of its subobjects. The direct base
12625 // classes of X are assigned first, in the order of their declaration in the
12626 // base-specifier-list, and then the immediate non-static data members of X
12627 // are assigned, in the order in which they were declared in the class
12628 // definition.
12629
12630 // Issue a warning if our implicit move assignment operator will move
12631 // from a virtual base more than once.
12632 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12633
12634 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12635
12636 // The exception specification is needed because we are defining the
12637 // function.
12638 ResolveExceptionSpec(CurrentLocation,
12639 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12640
12641 // Add a context note for diagnostics produced after this point.
12642 Scope.addContextNote(CurrentLocation);
12643
12644 // The statements that form the synthesized function body.
12645 SmallVector<Stmt*, 8> Statements;
12646
12647 // The parameter for the "other" object, which we are move from.
12648 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12649 QualType OtherRefType = Other->getType()->
12650 getAs<RValueReferenceType>()->getPointeeType();
12651
12652 // Our location for everything implicitly-generated.
12653 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12654 ? MoveAssignOperator->getEndLoc()
12655 : MoveAssignOperator->getLocation();
12656
12657 // Builds a reference to the "other" object.
12658 RefBuilder OtherRef(Other, OtherRefType);
12659 // Cast to rvalue.
12660 MoveCastBuilder MoveOther(OtherRef);
12661
12662 // Builds the "this" pointer.
12663 ThisBuilder This;
12664
12665 // Assign base classes.
12666 bool Invalid = false;
12667 for (auto &Base : ClassDecl->bases()) {
12668 // C++11 [class.copy]p28:
12669 // It is unspecified whether subobjects representing virtual base classes
12670 // are assigned more than once by the implicitly-defined copy assignment
12671 // operator.
12672 // FIXME: Do not assign to a vbase that will be assigned by some other base
12673 // class. For a move-assignment, this can result in the vbase being moved
12674 // multiple times.
12675
12676 // Form the assignment:
12677 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12678 QualType BaseType = Base.getType().getUnqualifiedType();
12679 if (!BaseType->isRecordType()) {
12680 Invalid = true;
12681 continue;
12682 }
12683
12684 CXXCastPath BasePath;
12685 BasePath.push_back(&Base);
12686
12687 // Construct the "from" expression, which is an implicit cast to the
12688 // appropriately-qualified base type.
12689 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12690
12691 // Dereference "this".
12692 DerefBuilder DerefThis(This);
12693
12694 // Implicitly cast "this" to the appropriately-qualified base type.
12695 CastBuilder To(DerefThis,
12696 Context.getQualifiedType(
12697 BaseType, MoveAssignOperator->getMethodQualifiers()),
12698 VK_LValue, BasePath);
12699
12700 // Build the move.
12701 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12702 To, From,
12703 /*CopyingBaseSubobject=*/true,
12704 /*Copying=*/false);
12705 if (Move.isInvalid()) {
12706 MoveAssignOperator->setInvalidDecl();
12707 return;
12708 }
12709
12710 // Success! Record the move.
12711 Statements.push_back(Move.getAs<Expr>());
12712 }
12713
12714 // Assign non-static members.
12715 for (auto *Field : ClassDecl->fields()) {
12716 // FIXME: We should form some kind of AST representation for the implied
12717 // memcpy in a union copy operation.
12718 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12719 continue;
12720
12721 if (Field->isInvalidDecl()) {
12722 Invalid = true;
12723 continue;
12724 }
12725
12726 // Check for members of reference type; we can't move those.
12727 if (Field->getType()->isReferenceType()) {
12728 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12729 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12730 Diag(Field->getLocation(), diag::note_declared_at);
12731 Invalid = true;
12732 continue;
12733 }
12734
12735 // Check for members of const-qualified, non-class type.
12736 QualType BaseType = Context.getBaseElementType(Field->getType());
12737 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12738 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12739 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12740 Diag(Field->getLocation(), diag::note_declared_at);
12741 Invalid = true;
12742 continue;
12743 }
12744
12745 // Suppress assigning zero-width bitfields.
12746 if (Field->isZeroLengthBitField(Context))
12747 continue;
12748
12749 QualType FieldType = Field->getType().getNonReferenceType();
12750 if (FieldType->isIncompleteArrayType()) {
12751 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12752, __PRETTY_FUNCTION__))
12752 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12752, __PRETTY_FUNCTION__))
;
12753 continue;
12754 }
12755
12756 // Build references to the field in the object we're copying from and to.
12757 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12758 LookupMemberName);
12759 MemberLookup.addDecl(Field);
12760 MemberLookup.resolveKind();
12761 MemberBuilder From(MoveOther, OtherRefType,
12762 /*IsArrow=*/false, MemberLookup);
12763 MemberBuilder To(This, getCurrentThisType(),
12764 /*IsArrow=*/true, MemberLookup);
12765
12766 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12768, __PRETTY_FUNCTION__))
12767 "Member reference with rvalue base must be rvalue except for reference "((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12768, __PRETTY_FUNCTION__))
12768 "members, which aren't allowed for move assignment.")((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? static_cast
<void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12768, __PRETTY_FUNCTION__))
;
12769
12770 // Build the move of this field.
12771 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12772 To, From,
12773 /*CopyingBaseSubobject=*/false,
12774 /*Copying=*/false);
12775 if (Move.isInvalid()) {
12776 MoveAssignOperator->setInvalidDecl();
12777 return;
12778 }
12779
12780 // Success! Record the copy.
12781 Statements.push_back(Move.getAs<Stmt>());
12782 }
12783
12784 if (!Invalid) {
12785 // Add a "return *this;"
12786 ExprResult ThisObj =
12787 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12788
12789 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12790 if (Return.isInvalid())
12791 Invalid = true;
12792 else
12793 Statements.push_back(Return.getAs<Stmt>());
12794 }
12795
12796 if (Invalid) {
12797 MoveAssignOperator->setInvalidDecl();
12798 return;
12799 }
12800
12801 StmtResult Body;
12802 {
12803 CompoundScopeRAII CompoundScope(*this);
12804 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12805 /*isStmtExpr=*/false);
12806 assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail"
) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12806, __PRETTY_FUNCTION__))
;
12807 }
12808 MoveAssignOperator->setBody(Body.getAs<Stmt>());
12809 MoveAssignOperator->markUsed(Context);
12810
12811 if (ASTMutationListener *L = getASTMutationListener()) {
12812 L->CompletedImplicitDefinition(MoveAssignOperator);
12813 }
12814}
12815
12816CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12817 CXXRecordDecl *ClassDecl) {
12818 // C++ [class.copy]p4:
12819 // If the class definition does not explicitly declare a copy
12820 // constructor, one is declared implicitly.
12821 assert(ClassDecl->needsImplicitCopyConstructor())((ClassDecl->needsImplicitCopyConstructor()) ? static_cast
<void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12821, __PRETTY_FUNCTION__))
;
12822
12823 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12824 if (DSM.isAlreadyBeingDeclared())
12825 return nullptr;
12826
12827 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12828 QualType ArgType = ClassType;
12829 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12830 if (Const)
12831 ArgType = ArgType.withConst();
12832
12833 if (Context.getLangOpts().OpenCLCPlusPlus)
12834 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12835
12836 ArgType = Context.getLValueReferenceType(ArgType);
12837
12838 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12839 CXXCopyConstructor,
12840 Const);
12841
12842 DeclarationName Name
12843 = Context.DeclarationNames.getCXXConstructorName(
12844 Context.getCanonicalType(ClassType));
12845 SourceLocation ClassLoc = ClassDecl->getLocation();
12846 DeclarationNameInfo NameInfo(Name, ClassLoc);
12847
12848 // An implicitly-declared copy constructor is an inline public
12849 // member of its class.
12850 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12851 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12852 ExplicitSpecifier(),
12853 /*isInline=*/true,
12854 /*isImplicitlyDeclared=*/true,
12855 Constexpr ? CSK_constexpr : CSK_unspecified);
12856 CopyConstructor->setAccess(AS_public);
12857 CopyConstructor->setDefaulted();
12858
12859 if (getLangOpts().CUDA) {
12860 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12861 CopyConstructor,
12862 /* ConstRHS */ Const,
12863 /* Diagnose */ false);
12864 }
12865
12866 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12867
12868 // Add the parameter to the constructor.
12869 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12870 ClassLoc, ClassLoc,
12871 /*IdentifierInfo=*/nullptr,
12872 ArgType, /*TInfo=*/nullptr,
12873 SC_None, nullptr);
12874 CopyConstructor->setParams(FromParam);
12875
12876 CopyConstructor->setTrivial(
12877 ClassDecl->needsOverloadResolutionForCopyConstructor()
12878 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12879 : ClassDecl->hasTrivialCopyConstructor());
12880
12881 CopyConstructor->setTrivialForCall(
12882 ClassDecl->hasAttr<TrivialABIAttr>() ||
12883 (ClassDecl->needsOverloadResolutionForCopyConstructor()
12884 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12885 TAH_ConsiderTrivialABI)
12886 : ClassDecl->hasTrivialCopyConstructorForCall()));
12887
12888 // Note that we have declared this constructor.
12889 ++getASTContext().NumImplicitCopyConstructorsDeclared;
12890
12891 Scope *S = getScopeForContext(ClassDecl);
12892 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12893
12894 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12895 ClassDecl->setImplicitCopyConstructorIsDeleted();
12896 SetDeclDeleted(CopyConstructor, ClassLoc);
12897 }
12898
12899 if (S)
12900 PushOnScopeChains(CopyConstructor, S, false);
12901 ClassDecl->addDecl(CopyConstructor);
12902
12903 return CopyConstructor;
12904}
12905
12906void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12907 CXXConstructorDecl *CopyConstructor) {
12908 assert((CopyConstructor->isDefaulted() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12912, __PRETTY_FUNCTION__))
12909 CopyConstructor->isCopyConstructor() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12912, __PRETTY_FUNCTION__))
12910 !CopyConstructor->doesThisDeclarationHaveABody() &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12912, __PRETTY_FUNCTION__))
12911 !CopyConstructor->isDeleted()) &&(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12912, __PRETTY_FUNCTION__))
12912 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(((CopyConstructor->isDefaulted() && CopyConstructor
->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody
() && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12912, __PRETTY_FUNCTION__))
;
12913 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12914 return;
12915
12916 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12917 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")((ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12917, __PRETTY_FUNCTION__))
;
12918
12919 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12920
12921 // The exception specification is needed because we are defining the
12922 // function.
12923 ResolveExceptionSpec(CurrentLocation,
12924 CopyConstructor->getType()->castAs<FunctionProtoType>());
12925 MarkVTableUsed(CurrentLocation, ClassDecl);
12926
12927 // Add a context note for diagnostics produced after this point.
12928 Scope.addContextNote(CurrentLocation);
12929
12930 // C++11 [class.copy]p7:
12931 // The [definition of an implicitly declared copy constructor] is
12932 // deprecated if the class has a user-declared copy assignment operator
12933 // or a user-declared destructor.
12934 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12935 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12936
12937 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12938 CopyConstructor->setInvalidDecl();
12939 } else {
12940 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12941 ? CopyConstructor->getEndLoc()
12942 : CopyConstructor->getLocation();
12943 Sema::CompoundScopeRAII CompoundScope(*this);
12944 CopyConstructor->setBody(
12945 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12946 CopyConstructor->markUsed(Context);
12947 }
12948
12949 if (ASTMutationListener *L = getASTMutationListener()) {
12950 L->CompletedImplicitDefinition(CopyConstructor);
12951 }
12952}
12953
12954CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12955 CXXRecordDecl *ClassDecl) {
12956 assert(ClassDecl->needsImplicitMoveConstructor())((ClassDecl->needsImplicitMoveConstructor()) ? static_cast
<void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 12956, __PRETTY_FUNCTION__))
;
12957
12958 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12959 if (DSM.isAlreadyBeingDeclared())
12960 return nullptr;
12961
12962 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12963
12964 QualType ArgType = ClassType;
12965 if (Context.getLangOpts().OpenCLCPlusPlus)
12966 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12967 ArgType = Context.getRValueReferenceType(ArgType);
12968
12969 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12970 CXXMoveConstructor,
12971 false);
12972
12973 DeclarationName Name
12974 = Context.DeclarationNames.getCXXConstructorName(
12975 Context.getCanonicalType(ClassType));
12976 SourceLocation ClassLoc = ClassDecl->getLocation();
12977 DeclarationNameInfo NameInfo(Name, ClassLoc);
12978
12979 // C++11 [class.copy]p11:
12980 // An implicitly-declared copy/move constructor is an inline public
12981 // member of its class.
12982 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12983 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12984 ExplicitSpecifier(),
12985 /*isInline=*/true,
12986 /*isImplicitlyDeclared=*/true,
12987 Constexpr ? CSK_constexpr : CSK_unspecified);
12988 MoveConstructor->setAccess(AS_public);
12989 MoveConstructor->setDefaulted();
12990
12991 if (getLangOpts().CUDA) {
12992 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12993 MoveConstructor,
12994 /* ConstRHS */ false,
12995 /* Diagnose */ false);
12996 }
12997
12998 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12999
13000 // Add the parameter to the constructor.
13001 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
13002 ClassLoc, ClassLoc,
13003 /*IdentifierInfo=*/nullptr,
13004 ArgType, /*TInfo=*/nullptr,
13005 SC_None, nullptr);
13006 MoveConstructor->setParams(FromParam);
13007
13008 MoveConstructor->setTrivial(
13009 ClassDecl->needsOverloadResolutionForMoveConstructor()
13010 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
13011 : ClassDecl->hasTrivialMoveConstructor());
13012
13013 MoveConstructor->setTrivialForCall(
13014 ClassDecl->hasAttr<TrivialABIAttr>() ||
13015 (ClassDecl->needsOverloadResolutionForMoveConstructor()
13016 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
13017 TAH_ConsiderTrivialABI)
13018 : ClassDecl->hasTrivialMoveConstructorForCall()));
13019
13020 // Note that we have declared this constructor.
13021 ++getASTContext().NumImplicitMoveConstructorsDeclared;
13022
13023 Scope *S = getScopeForContext(ClassDecl);
13024 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
13025
13026 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
13027 ClassDecl->setImplicitMoveConstructorIsDeleted();
13028 SetDeclDeleted(MoveConstructor, ClassLoc);
13029 }
13030
13031 if (S)
13032 PushOnScopeChains(MoveConstructor, S, false);
13033 ClassDecl->addDecl(MoveConstructor);
13034
13035 return MoveConstructor;
13036}
13037
13038void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
13039 CXXConstructorDecl *MoveConstructor) {
13040 assert((MoveConstructor->isDefaulted() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13044, __PRETTY_FUNCTION__))
13041 MoveConstructor->isMoveConstructor() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13044, __PRETTY_FUNCTION__))
13042 !MoveConstructor->doesThisDeclarationHaveABody() &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13044, __PRETTY_FUNCTION__))
13043 !MoveConstructor->isDeleted()) &&(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13044, __PRETTY_FUNCTION__))
13044 "DefineImplicitMoveConstructor - call it for implicit move ctor")(((MoveConstructor->isDefaulted() && MoveConstructor
->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody
() && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13044, __PRETTY_FUNCTION__))
;
13045 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
13046 return;
13047
13048 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
13049 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")((ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13049, __PRETTY_FUNCTION__))
;
13050
13051 SynthesizedFunctionScope Scope(*this, MoveConstructor);
13052
13053 // The exception specification is needed because we are defining the
13054 // function.
13055 ResolveExceptionSpec(CurrentLocation,
13056 MoveConstructor->getType()->castAs<FunctionProtoType>());
13057 MarkVTableUsed(CurrentLocation, ClassDecl);
13058
13059 // Add a context note for diagnostics produced after this point.
13060 Scope.addContextNote(CurrentLocation);
13061
13062 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
13063 MoveConstructor->setInvalidDecl();
13064 } else {
13065 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
13066 ? MoveConstructor->getEndLoc()
13067 : MoveConstructor->getLocation();
13068 Sema::CompoundScopeRAII CompoundScope(*this);
13069 MoveConstructor->setBody(ActOnCompoundStmt(
13070 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
13071 MoveConstructor->markUsed(Context);
13072 }
13073
13074 if (ASTMutationListener *L = getASTMutationListener()) {
13075 L->CompletedImplicitDefinition(MoveConstructor);
13076 }
13077}
13078
13079bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
13080 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
13081}
13082
13083void Sema::DefineImplicitLambdaToFunctionPointerConversion(
13084 SourceLocation CurrentLocation,
13085 CXXConversionDecl *Conv) {
13086 SynthesizedFunctionScope Scope(*this, Conv);
13087 assert(!Conv->getReturnType()->isUndeducedType())((!Conv->getReturnType()->isUndeducedType()) ? static_cast
<void> (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13087, __PRETTY_FUNCTION__))
;
13088
13089 CXXRecordDecl *Lambda = Conv->getParent();
13090 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
13091 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
13092
13093 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
13094 CallOp = InstantiateFunctionDeclaration(
13095 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13096 if (!CallOp)
13097 return;
13098
13099 Invoker = InstantiateFunctionDeclaration(
13100 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13101 if (!Invoker)
13102 return;
13103 }
13104
13105 if (CallOp->isInvalidDecl())
13106 return;
13107
13108 // Mark the call operator referenced (and add to pending instantiations
13109 // if necessary).
13110 // For both the conversion and static-invoker template specializations
13111 // we construct their body's in this function, so no need to add them
13112 // to the PendingInstantiations.
13113 MarkFunctionReferenced(CurrentLocation, CallOp);
13114
13115 // Fill in the __invoke function with a dummy implementation. IR generation
13116 // will fill in the actual details. Update its type in case it contained
13117 // an 'auto'.
13118 Invoker->markUsed(Context);
13119 Invoker->setReferenced();
13120 Invoker->setType(Conv->getReturnType()->getPointeeType());
13121 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
13122
13123 // Construct the body of the conversion function { return __invoke; }.
13124 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
13125 VK_LValue, Conv->getLocation());
13126 assert(FunctionRef && "Can't refer to __invoke function?")((FunctionRef && "Can't refer to __invoke function?")
? static_cast<void> (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13126, __PRETTY_FUNCTION__))
;
13127 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
13128 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
13129 Conv->getLocation()));
13130 Conv->markUsed(Context);
13131 Conv->setReferenced();
13132
13133 if (ASTMutationListener *L = getASTMutationListener()) {
13134 L->CompletedImplicitDefinition(Conv);
13135 L->CompletedImplicitDefinition(Invoker);
13136 }
13137}
13138
13139
13140
13141void Sema::DefineImplicitLambdaToBlockPointerConversion(
13142 SourceLocation CurrentLocation,
13143 CXXConversionDecl *Conv)
13144{
13145 assert(!Conv->getParent()->isGenericLambda())((!Conv->getParent()->isGenericLambda()) ? static_cast<
void> (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13145, __PRETTY_FUNCTION__))
;
13146
13147 SynthesizedFunctionScope Scope(*this, Conv);
13148
13149 // Copy-initialize the lambda object as needed to capture it.
13150 Expr *This = ActOnCXXThis(CurrentLocation).get();
13151 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
13152
13153 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
13154 Conv->getLocation(),
13155 Conv, DerefThis);
13156
13157 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
13158 // behavior. Note that only the general conversion function does this
13159 // (since it's unusable otherwise); in the case where we inline the
13160 // block literal, it has block literal lifetime semantics.
13161 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
13162 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
13163 CK_CopyAndAutoreleaseBlockObject,
13164 BuildBlock.get(), nullptr, VK_RValue);
13165
13166 if (BuildBlock.isInvalid()) {
13167 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13168 Conv->setInvalidDecl();
13169 return;
13170 }
13171
13172 // Create the return statement that returns the block from the conversion
13173 // function.
13174 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
13175 if (Return.isInvalid()) {
13176 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13177 Conv->setInvalidDecl();
13178 return;
13179 }
13180
13181 // Set the body of the conversion function.
13182 Stmt *ReturnS = Return.get();
13183 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
13184 Conv->getLocation()));
13185 Conv->markUsed(Context);
13186
13187 // We're done; notify the mutation listener, if any.
13188 if (ASTMutationListener *L = getASTMutationListener()) {
13189 L->CompletedImplicitDefinition(Conv);
13190 }
13191}
13192
13193/// Determine whether the given list arguments contains exactly one
13194/// "real" (non-default) argument.
13195static bool hasOneRealArgument(MultiExprArg Args) {
13196 switch (Args.size()) {
13197 case 0:
13198 return false;
13199
13200 default:
13201 if (!Args[1]->isDefaultArgument())
13202 return false;
13203
13204 LLVM_FALLTHROUGH[[gnu::fallthrough]];
13205 case 1:
13206 return !Args[0]->isDefaultArgument();
13207 }
13208
13209 return false;
13210}
13211
13212ExprResult
13213Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13214 NamedDecl *FoundDecl,
13215 CXXConstructorDecl *Constructor,
13216 MultiExprArg ExprArgs,
13217 bool HadMultipleCandidates,
13218 bool IsListInitialization,
13219 bool IsStdInitListInitialization,
13220 bool RequiresZeroInit,
13221 unsigned ConstructKind,
13222 SourceRange ParenRange) {
13223 bool Elidable = false;
13224
13225 // C++0x [class.copy]p34:
13226 // When certain criteria are met, an implementation is allowed to
13227 // omit the copy/move construction of a class object, even if the
13228 // copy/move constructor and/or destructor for the object have
13229 // side effects. [...]
13230 // - when a temporary class object that has not been bound to a
13231 // reference (12.2) would be copied/moved to a class object
13232 // with the same cv-unqualified type, the copy/move operation
13233 // can be omitted by constructing the temporary object
13234 // directly into the target of the omitted copy/move
13235 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13236 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13237 Expr *SubExpr = ExprArgs[0];
13238 Elidable = SubExpr->isTemporaryObject(
13239 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13240 }
13241
13242 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13243 FoundDecl, Constructor,
13244 Elidable, ExprArgs, HadMultipleCandidates,
13245 IsListInitialization,
13246 IsStdInitListInitialization, RequiresZeroInit,
13247 ConstructKind, ParenRange);
13248}
13249
13250ExprResult
13251Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13252 NamedDecl *FoundDecl,
13253 CXXConstructorDecl *Constructor,
13254 bool Elidable,
13255 MultiExprArg ExprArgs,
13256 bool HadMultipleCandidates,
13257 bool IsListInitialization,
13258 bool IsStdInitListInitialization,
13259 bool RequiresZeroInit,
13260 unsigned ConstructKind,
13261 SourceRange ParenRange) {
13262 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13263 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13264 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13265 return ExprError();
13266 }
13267
13268 return BuildCXXConstructExpr(
13269 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13270 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13271 RequiresZeroInit, ConstructKind, ParenRange);
13272}
13273
13274/// BuildCXXConstructExpr - Creates a complete call to a constructor,
13275/// including handling of its default argument expressions.
13276ExprResult
13277Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13278 CXXConstructorDecl *Constructor,
13279 bool Elidable,
13280 MultiExprArg ExprArgs,
13281 bool HadMultipleCandidates,
13282 bool IsListInitialization,
13283 bool IsStdInitListInitialization,
13284 bool RequiresZeroInit,
13285 unsigned ConstructKind,
13286 SourceRange ParenRange) {
13287 assert(declaresSameEntity(((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13290, __PRETTY_FUNCTION__))
13288 Constructor->getParent(),((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13290, __PRETTY_FUNCTION__))
13289 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13290, __PRETTY_FUNCTION__))
13290 "given constructor for wrong type")((declaresSameEntity( Constructor->getParent(), DeclInitType
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
"given constructor for wrong type") ? static_cast<void>
(0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13290, __PRETTY_FUNCTION__))
;
13291 MarkFunctionReferenced(ConstructLoc, Constructor);
13292 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13293 return ExprError();
13294
13295 return CXXConstructExpr::Create(
13296 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13297 ExprArgs, HadMultipleCandidates, IsListInitialization,
13298 IsStdInitListInitialization, RequiresZeroInit,
13299 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13300 ParenRange);
13301}
13302
13303ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13304 assert(Field->hasInClassInitializer())((Field->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Field->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13304, __PRETTY_FUNCTION__))
;
13305
13306 // If we already have the in-class initializer nothing needs to be done.
13307 if (Field->getInClassInitializer())
13308 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13309
13310 // If we might have already tried and failed to instantiate, don't try again.
13311 if (Field->isInvalidDecl())
13312 return ExprError();
13313
13314 // Maybe we haven't instantiated the in-class initializer. Go check the
13315 // pattern FieldDecl to see if it has one.
13316 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13317
13318 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13319 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13320 DeclContext::lookup_result Lookup =
13321 ClassPattern->lookup(Field->getDeclName());
13322
13323 // Lookup can return at most two results: the pattern for the field, or the
13324 // injected class name of the parent record. No other member can have the
13325 // same name as the field.
13326 // In modules mode, lookup can return multiple results (coming from
13327 // different modules).
13328 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&(((getLangOpts().Modules || (!Lookup.empty() && Lookup
.size() <= 2)) && "more than two lookup results for field name"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13329, __PRETTY_FUNCTION__))
13329 "more than two lookup results for field name")(((getLangOpts().Modules || (!Lookup.empty() && Lookup
.size() <= 2)) && "more than two lookup results for field name"
) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13329, __PRETTY_FUNCTION__))
;
13330 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13331 if (!Pattern) {
13332 assert(isa<CXXRecordDecl>(Lookup[0]) &&((isa<CXXRecordDecl>(Lookup[0]) && "cannot have other non-field member with same name"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13333, __PRETTY_FUNCTION__))
13333 "cannot have other non-field member with same name")((isa<CXXRecordDecl>(Lookup[0]) && "cannot have other non-field member with same name"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13333, __PRETTY_FUNCTION__))
;
13334 for (auto L : Lookup)
13335 if (isa<FieldDecl>(L)) {
13336 Pattern = cast<FieldDecl>(L);
13337 break;
13338 }
13339 assert(Pattern && "We must have set the Pattern!")((Pattern && "We must have set the Pattern!") ? static_cast
<void> (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13339, __PRETTY_FUNCTION__))
;
13340 }
13341
13342 if (!Pattern->hasInClassInitializer() ||
13343 InstantiateInClassInitializer(Loc, Field, Pattern,
13344 getTemplateInstantiationArgs(Field))) {
13345 // Don't diagnose this again.
13346 Field->setInvalidDecl();
13347 return ExprError();
13348 }
13349 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13350 }
13351
13352 // DR1351:
13353 // If the brace-or-equal-initializer of a non-static data member
13354 // invokes a defaulted default constructor of its class or of an
13355 // enclosing class in a potentially evaluated subexpression, the
13356 // program is ill-formed.
13357 //
13358 // This resolution is unworkable: the exception specification of the
13359 // default constructor can be needed in an unevaluated context, in
13360 // particular, in the operand of a noexcept-expression, and we can be
13361 // unable to compute an exception specification for an enclosed class.
13362 //
13363 // Any attempt to resolve the exception specification of a defaulted default
13364 // constructor before the initializer is lexically complete will ultimately
13365 // come here at which point we can diagnose it.
13366 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13367 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13368 << OutermostClass << Field;
13369 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13370 // Recover by marking the field invalid, unless we're in a SFINAE context.
13371 if (!isSFINAEContext())
13372 Field->setInvalidDecl();
13373 return ExprError();
13374}
13375
13376void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13377 if (VD->isInvalidDecl()) return;
13378
13379 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13380 if (ClassDecl->isInvalidDecl()) return;
13381 if (ClassDecl->hasIrrelevantDestructor()) return;
13382 if (ClassDecl->isDependentContext()) return;
13383
13384 if (VD->isNoDestroy(getASTContext()))
13385 return;
13386
13387 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13388
13389 // If this is an array, we'll require the destructor during initialization, so
13390 // we can skip over this. We still want to emit exit-time destructor warnings
13391 // though.
13392 if (!VD->getType()->isArrayType()) {
13393 MarkFunctionReferenced(VD->getLocation(), Destructor);
13394 CheckDestructorAccess(VD->getLocation(), Destructor,
13395 PDiag(diag::err_access_dtor_var)
13396 << VD->getDeclName() << VD->getType());
13397 DiagnoseUseOfDecl(Destructor, VD->getLocation());
13398 }
13399
13400 if (Destructor->isTrivial()) return;
13401
13402 // If the destructor is constexpr, check whether the variable has constant
13403 // destruction now.
13404 if (Destructor->isConstexpr() && VD->getInit() &&
13405 !VD->getInit()->isValueDependent() && VD->evaluateValue()) {
13406 SmallVector<PartialDiagnosticAt, 8> Notes;
13407 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) {
13408 Diag(VD->getLocation(),
13409 diag::err_constexpr_var_requires_const_destruction) << VD;
13410 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13411 Diag(Notes[I].first, Notes[I].second);
13412 }
13413 }
13414
13415 if (!VD->hasGlobalStorage()) return;
13416
13417 // Emit warning for non-trivial dtor in global scope (a real global,
13418 // class-static, function-static).
13419 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13420
13421 // TODO: this should be re-enabled for static locals by !CXAAtExit
13422 if (!VD->isStaticLocal())
13423 Diag(VD->getLocation(), diag::warn_global_destructor);
13424}
13425
13426/// Given a constructor and the set of arguments provided for the
13427/// constructor, convert the arguments and add any required default arguments
13428/// to form a proper call to this constructor.
13429///
13430/// \returns true if an error occurred, false otherwise.
13431bool
13432Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13433 MultiExprArg ArgsPtr,
13434 SourceLocation Loc,
13435 SmallVectorImpl<Expr*> &ConvertedArgs,
13436 bool AllowExplicit,
13437 bool IsListInitialization) {
13438 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13439 unsigned NumArgs = ArgsPtr.size();
13440 Expr **Args = ArgsPtr.data();
13441
13442 const FunctionProtoType *Proto
13443 = Constructor->getType()->getAs<FunctionProtoType>();
13444 assert(Proto && "Constructor without a prototype?")((Proto && "Constructor without a prototype?") ? static_cast
<void> (0) : __assert_fail ("Proto && \"Constructor without a prototype?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13444, __PRETTY_FUNCTION__))
;
13445 unsigned NumParams = Proto->getNumParams();
13446
13447 // If too few arguments are available, we'll fill in the rest with defaults.
13448 if (NumArgs < NumParams)
13449 ConvertedArgs.reserve(NumParams);
13450 else
13451 ConvertedArgs.reserve(NumArgs);
13452
13453 VariadicCallType CallType =
13454 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13455 SmallVector<Expr *, 8> AllArgs;
13456 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13457 Proto, 0,
13458 llvm::makeArrayRef(Args, NumArgs),
13459 AllArgs,
13460 CallType, AllowExplicit,
13461 IsListInitialization);
13462 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13463
13464 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13465
13466 CheckConstructorCall(Constructor,
13467 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13468 Proto, Loc);
13469
13470 return Invalid;
13471}
13472
13473static inline bool
13474CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13475 const FunctionDecl *FnDecl) {
13476 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13477 if (isa<NamespaceDecl>(DC)) {
13478 return SemaRef.Diag(FnDecl->getLocation(),
13479 diag::err_operator_new_delete_declared_in_namespace)
13480 << FnDecl->getDeclName();
13481 }
13482
13483 if (isa<TranslationUnitDecl>(DC) &&
13484 FnDecl->getStorageClass() == SC_Static) {
13485 return SemaRef.Diag(FnDecl->getLocation(),
13486 diag::err_operator_new_delete_declared_static)
13487 << FnDecl->getDeclName();
13488 }
13489
13490 return false;
13491}
13492
13493static QualType
13494RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13495 QualType QTy = PtrTy->getPointeeType();
13496 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13497 return SemaRef.Context.getPointerType(QTy);
13498}
13499
13500static inline bool
13501CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13502 CanQualType ExpectedResultType,
13503 CanQualType ExpectedFirstParamType,
13504 unsigned DependentParamTypeDiag,
13505 unsigned InvalidParamTypeDiag) {
13506 QualType ResultType =
13507 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13508
13509 // Check that the result type is not dependent.
13510 if (ResultType->isDependentType())
13511 return SemaRef.Diag(FnDecl->getLocation(),
13512 diag::err_operator_new_delete_dependent_result_type)
13513 << FnDecl->getDeclName() << ExpectedResultType;
13514
13515 // The operator is valid on any address space for OpenCL.
13516 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13517 if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13518 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13519 }
13520 }
13521
13522 // Check that the result type is what we expect.
13523 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13524 return SemaRef.Diag(FnDecl->getLocation(),
13525 diag::err_operator_new_delete_invalid_result_type)
13526 << FnDecl->getDeclName() << ExpectedResultType;
13527
13528 // A function template must have at least 2 parameters.
13529 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13530 return SemaRef.Diag(FnDecl->getLocation(),
13531 diag::err_operator_new_delete_template_too_few_parameters)
13532 << FnDecl->getDeclName();
13533
13534 // The function decl must have at least 1 parameter.
13535 if (FnDecl->getNumParams() == 0)
13536 return SemaRef.Diag(FnDecl->getLocation(),
13537 diag::err_operator_new_delete_too_few_parameters)
13538 << FnDecl->getDeclName();
13539
13540 // Check the first parameter type is not dependent.
13541 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13542 if (FirstParamType->isDependentType())
13543 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13544 << FnDecl->getDeclName() << ExpectedFirstParamType;
13545
13546 // Check that the first parameter type is what we expect.
13547 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13548 // The operator is valid on any address space for OpenCL.
13549 if (auto *PtrTy =
13550 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13551 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13552 }
13553 }
13554 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13555 ExpectedFirstParamType)
13556 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13557 << FnDecl->getDeclName() << ExpectedFirstParamType;
13558
13559 return false;
13560}
13561
13562static bool
13563CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13564 // C++ [basic.stc.dynamic.allocation]p1:
13565 // A program is ill-formed if an allocation function is declared in a
13566 // namespace scope other than global scope or declared static in global
13567 // scope.
13568 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13569 return true;
13570
13571 CanQualType SizeTy =
13572 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13573
13574 // C++ [basic.stc.dynamic.allocation]p1:
13575 // The return type shall be void*. The first parameter shall have type
13576 // std::size_t.
13577 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13578 SizeTy,
13579 diag::err_operator_new_dependent_param_type,
13580 diag::err_operator_new_param_type))
13581 return true;
13582
13583 // C++ [basic.stc.dynamic.allocation]p1:
13584 // The first parameter shall not have an associated default argument.
13585 if (FnDecl->getParamDecl(0)->hasDefaultArg())
13586 return SemaRef.Diag(FnDecl->getLocation(),
13587 diag::err_operator_new_default_arg)
13588 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13589
13590 return false;
13591}
13592
13593static bool
13594CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13595 // C++ [basic.stc.dynamic.deallocation]p1:
13596 // A program is ill-formed if deallocation functions are declared in a
13597 // namespace scope other than global scope or declared static in global
13598 // scope.
13599 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13600 return true;
13601
13602 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13603
13604 // C++ P0722:
13605 // Within a class C, the first parameter of a destroying operator delete
13606 // shall be of type C *. The first parameter of any other deallocation
13607 // function shall be of type void *.
13608 CanQualType ExpectedFirstParamType =
13609 MD && MD->isDestroyingOperatorDelete()
13610 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13611 SemaRef.Context.getRecordType(MD->getParent())))
13612 : SemaRef.Context.VoidPtrTy;
13613
13614 // C++ [basic.stc.dynamic.deallocation]p2:
13615 // Each deallocation function shall return void
13616 if (CheckOperatorNewDeleteTypes(
13617 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13618 diag::err_operator_delete_dependent_param_type,
13619 diag::err_operator_delete_param_type))
13620 return true;
13621
13622 // C++ P0722:
13623 // A destroying operator delete shall be a usual deallocation function.
13624 if (MD && !MD->getParent()->isDependentContext() &&
13625 MD->isDestroyingOperatorDelete() &&
13626 !SemaRef.isUsualDeallocationFunction(MD)) {
13627 SemaRef.Diag(MD->getLocation(),
13628 diag::err_destroying_operator_delete_not_usual);
13629 return true;
13630 }
13631
13632 return false;
13633}
13634
13635/// CheckOverloadedOperatorDeclaration - Check whether the declaration
13636/// of this overloaded operator is well-formed. If so, returns false;
13637/// otherwise, emits appropriate diagnostics and returns true.
13638bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13639 assert(FnDecl && FnDecl->isOverloadedOperator() &&((FnDecl && FnDecl->isOverloadedOperator() &&
"Expected an overloaded operator declaration") ? static_cast
<void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13640, __PRETTY_FUNCTION__))
13640 "Expected an overloaded operator declaration")((FnDecl && FnDecl->isOverloadedOperator() &&
"Expected an overloaded operator declaration") ? static_cast
<void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13640, __PRETTY_FUNCTION__))
;
13641
13642 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13643
13644 // C++ [over.oper]p5:
13645 // The allocation and deallocation functions, operator new,
13646 // operator new[], operator delete and operator delete[], are
13647 // described completely in 3.7.3. The attributes and restrictions
13648 // found in the rest of this subclause do not apply to them unless
13649 // explicitly stated in 3.7.3.
13650 if (Op == OO_Delete || Op == OO_Array_Delete)
13651 return CheckOperatorDeleteDeclaration(*this, FnDecl);
13652
13653 if (Op == OO_New || Op == OO_Array_New)
13654 return CheckOperatorNewDeclaration(*this, FnDecl);
13655
13656 // C++ [over.oper]p6:
13657 // An operator function shall either be a non-static member
13658 // function or be a non-member function and have at least one
13659 // parameter whose type is a class, a reference to a class, an
13660 // enumeration, or a reference to an enumeration.
13661 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13662 if (MethodDecl->isStatic())
13663 return Diag(FnDecl->getLocation(),
13664 diag::err_operator_overload_static) << FnDecl->getDeclName();
13665 } else {
13666 bool ClassOrEnumParam = false;
13667 for (auto Param : FnDecl->parameters()) {
13668 QualType ParamType = Param->getType().getNonReferenceType();
13669 if (ParamType->isDependentType() || ParamType->isRecordType() ||
13670 ParamType->isEnumeralType()) {
13671 ClassOrEnumParam = true;
13672 break;
13673 }
13674 }
13675
13676 if (!ClassOrEnumParam)
13677 return Diag(FnDecl->getLocation(),
13678 diag::err_operator_overload_needs_class_or_enum)
13679 << FnDecl->getDeclName();
13680 }
13681
13682 // C++ [over.oper]p8:
13683 // An operator function cannot have default arguments (8.3.6),
13684 // except where explicitly stated below.
13685 //
13686 // Only the function-call operator allows default arguments
13687 // (C++ [over.call]p1).
13688 if (Op != OO_Call) {
13689 for (auto Param : FnDecl->parameters()) {
13690 if (Param->hasDefaultArg())
13691 return Diag(Param->getLocation(),
13692 diag::err_operator_overload_default_arg)
13693 << FnDecl->getDeclName() << Param->getDefaultArgRange();
13694 }
13695 }
13696
13697 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13698 { false, false, false }
13699#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13700 , { Unary, Binary, MemberOnly }
13701#include "clang/Basic/OperatorKinds.def"
13702 };
13703
13704 bool CanBeUnaryOperator = OperatorUses[Op][0];
13705 bool CanBeBinaryOperator = OperatorUses[Op][1];
13706 bool MustBeMemberOperator = OperatorUses[Op][2];
13707
13708 // C++ [over.oper]p8:
13709 // [...] Operator functions cannot have more or fewer parameters
13710 // than the number required for the corresponding operator, as
13711 // described in the rest of this subclause.
13712 unsigned NumParams = FnDecl->getNumParams()
13713 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13714 if (Op != OO_Call &&
13715 ((NumParams == 1 && !CanBeUnaryOperator) ||
13716 (NumParams == 2 && !CanBeBinaryOperator) ||
13717 (NumParams < 1) || (NumParams > 2))) {
13718 // We have the wrong number of parameters.
13719 unsigned ErrorKind;
13720 if (CanBeUnaryOperator && CanBeBinaryOperator) {
13721 ErrorKind = 2; // 2 -> unary or binary.
13722 } else if (CanBeUnaryOperator) {
13723 ErrorKind = 0; // 0 -> unary
13724 } else {
13725 assert(CanBeBinaryOperator &&((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13726, __PRETTY_FUNCTION__))
13726 "All non-call overloaded operators are unary or binary!")((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 13726, __PRETTY_FUNCTION__))
;
13727 ErrorKind = 1; // 1 -> binary
13728 }
13729
13730 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13731 << FnDecl->getDeclName() << NumParams << ErrorKind;
13732 }
13733
13734 // Overloaded operators other than operator() cannot be variadic.
13735 if (Op != OO_Call &&
13736 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13737 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13738 << FnDecl->getDeclName();
13739 }
13740
13741 // Some operators must be non-static member functions.
13742 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13743 return Diag(FnDecl->getLocation(),
13744 diag::err_operator_overload_must_be_member)
13745 << FnDecl->getDeclName();
13746 }
13747
13748 // C++ [over.inc]p1:
13749 // The user-defined function called operator++ implements the
13750 // prefix and postfix ++ operator. If this function is a member
13751 // function with no parameters, or a non-member function with one
13752 // parameter of class or enumeration type, it defines the prefix
13753 // increment operator ++ for objects of that type. If the function
13754 // is a member function with one parameter (which shall be of type
13755 // int) or a non-member function with two parameters (the second
13756 // of which shall be of type int), it defines the postfix
13757 // increment operator ++ for objects of that type.
13758 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13759 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13760 QualType ParamType = LastParam->getType();
13761
13762 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13763 !ParamType->isDependentType())
13764 return Diag(LastParam->getLocation(),
13765 diag::err_operator_overload_post_incdec_must_be_int)
13766 << LastParam->getType() << (Op == OO_MinusMinus);
13767 }
13768
13769 return false;
13770}
13771
13772static bool
13773checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13774 FunctionTemplateDecl *TpDecl) {
13775 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13776
13777 // Must have one or two template parameters.
13778 if (TemplateParams->size() == 1) {
13779 NonTypeTemplateParmDecl *PmDecl =
13780 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13781
13782 // The template parameter must be a char parameter pack.
13783 if (PmDecl && PmDecl->isTemplateParameterPack() &&
13784 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13785 return false;
13786
13787 } else if (TemplateParams->size() == 2) {
13788 TemplateTypeParmDecl *PmType =
13789 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13790 NonTypeTemplateParmDecl *PmArgs =
13791 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13792
13793 // The second template parameter must be a parameter pack with the
13794 // first template parameter as its type.
13795 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13796 PmArgs->isTemplateParameterPack()) {
13797 const TemplateTypeParmType *TArgs =
13798 PmArgs->getType()->getAs<TemplateTypeParmType>();
13799 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13800 TArgs->getIndex() == PmType->getIndex()) {
13801 if (!SemaRef.inTemplateInstantiation())
13802 SemaRef.Diag(TpDecl->getLocation(),
13803 diag::ext_string_literal_operator_template);
13804 return false;
13805 }
13806 }
13807 }
13808
13809 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13810 diag::err_literal_operator_template)
13811 << TpDecl->getTemplateParameters()->getSourceRange();
13812 return true;
13813}
13814
13815/// CheckLiteralOperatorDeclaration - Check whether the declaration
13816/// of this literal operator function is well-formed. If so, returns
13817/// false; otherwise, emits appropriate diagnostics and returns true.
13818bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13819 if (isa<CXXMethodDecl>(FnDecl)) {
13820 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13821 << FnDecl->getDeclName();
13822 return true;
13823 }
13824
13825 if (FnDecl->isExternC()) {
13826 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13827 if (const LinkageSpecDecl *LSD =
13828 FnDecl->getDeclContext()->getExternCContext())
13829 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13830 return true;
13831 }
13832
13833 // This might be the definition of a literal operator template.
13834 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13835
13836 // This might be a specialization of a literal operator template.
13837 if (!TpDecl)
13838 TpDecl = FnDecl->getPrimaryTemplate();
13839
13840 // template <char...> type operator "" name() and
13841 // template <class T, T...> type operator "" name() are the only valid
13842 // template signatures, and the only valid signatures with no parameters.
13843 if (TpDecl) {
13844 if (FnDecl->param_size() != 0) {
13845 Diag(FnDecl->getLocation(),
13846 diag::err_literal_operator_template_with_params);
13847 return true;
13848 }
13849
13850 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13851 return true;
13852
13853 } else if (FnDecl->param_size() == 1) {
13854 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13855
13856 QualType ParamType = Param->getType().getUnqualifiedType();
13857
13858 // Only unsigned long long int, long double, any character type, and const
13859 // char * are allowed as the only parameters.
13860 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13861 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13862 Context.hasSameType(ParamType, Context.CharTy) ||
13863 Context.hasSameType(ParamType, Context.WideCharTy) ||
13864 Context.hasSameType(ParamType, Context.Char8Ty) ||
13865 Context.hasSameType(ParamType, Context.Char16Ty) ||
13866 Context.hasSameType(ParamType, Context.Char32Ty)) {
13867 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13868 QualType InnerType = Ptr->getPointeeType();
13869
13870 // Pointer parameter must be a const char *.
13871 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13872 Context.CharTy) &&
13873 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13874 Diag(Param->getSourceRange().getBegin(),
13875 diag::err_literal_operator_param)
13876 << ParamType << "'const char *'" << Param->getSourceRange();
13877 return true;
13878 }
13879
13880 } else if (ParamType->isRealFloatingType()) {
13881 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13882 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13883 return true;
13884
13885 } else if (ParamType->isIntegerType()) {
13886 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13887 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13888 return true;
13889
13890 } else {
13891 Diag(Param->getSourceRange().getBegin(),
13892 diag::err_literal_operator_invalid_param)
13893 << ParamType << Param->getSourceRange();
13894 return true;
13895 }
13896
13897 } else if (FnDecl->param_size() == 2) {
13898 FunctionDecl::param_iterator Param = FnDecl->param_begin();
13899
13900 // First, verify that the first parameter is correct.
13901
13902 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13903
13904 // Two parameter function must have a pointer to const as a
13905 // first parameter; let's strip those qualifiers.
13906 const PointerType *PT = FirstParamType->getAs<PointerType>();
13907
13908 if (!PT) {
13909 Diag((*Param)->getSourceRange().getBegin(),
13910 diag::err_literal_operator_param)
13911 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13912 return true;
13913 }
13914
13915 QualType PointeeType = PT->getPointeeType();
13916 // First parameter must be const
13917 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13918 Diag((*Param)->getSourceRange().getBegin(),
13919 diag::err_literal_operator_param)
13920 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13921 return true;
13922 }
13923
13924 QualType InnerType = PointeeType.getUnqualifiedType();
13925 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13926 // const char32_t* are allowed as the first parameter to a two-parameter
13927 // function
13928 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13929 Context.hasSameType(InnerType, Context.WideCharTy) ||
13930 Context.hasSameType(InnerType, Context.Char8Ty) ||
13931 Context.hasSameType(InnerType, Context.Char16Ty) ||
13932 Context.hasSameType(InnerType, Context.Char32Ty))) {
13933 Diag((*Param)->getSourceRange().getBegin(),
13934 diag::err_literal_operator_param)
13935 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13936 return true;
13937 }
13938
13939 // Move on to the second and final parameter.
13940 ++Param;
13941
13942 // The second parameter must be a std::size_t.
13943 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13944 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13945 Diag((*Param)->getSourceRange().getBegin(),
13946 diag::err_literal_operator_param)
13947 << SecondParamType << Context.getSizeType()
13948 << (*Param)->getSourceRange();
13949 return true;
13950 }
13951 } else {
13952 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13953 return true;
13954 }
13955
13956 // Parameters are good.
13957
13958 // A parameter-declaration-clause containing a default argument is not
13959 // equivalent to any of the permitted forms.
13960 for (auto Param : FnDecl->parameters()) {
13961 if (Param->hasDefaultArg()) {
13962 Diag(Param->getDefaultArgRange().getBegin(),
13963 diag::err_literal_operator_default_argument)
13964 << Param->getDefaultArgRange();
13965 break;
13966 }
13967 }
13968
13969 StringRef LiteralName
13970 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13971 if (LiteralName[0] != '_' &&
13972 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13973 // C++11 [usrlit.suffix]p1:
13974 // Literal suffix identifiers that do not start with an underscore
13975 // are reserved for future standardization.
13976 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13977 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13978 }
13979
13980 return false;
13981}
13982
13983/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13984/// linkage specification, including the language and (if present)
13985/// the '{'. ExternLoc is the location of the 'extern', Lang is the
13986/// language string literal. LBraceLoc, if valid, provides the location of
13987/// the '{' brace. Otherwise, this linkage specification does not
13988/// have any braces.
13989Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13990 Expr *LangStr,
13991 SourceLocation LBraceLoc) {
13992 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13993 if (!Lit->isAscii()) {
13994 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13995 << LangStr->getSourceRange();
13996 return nullptr;
13997 }
13998
13999 StringRef Lang = Lit->getString();
14000 LinkageSpecDecl::LanguageIDs Language;
14001 if (Lang == "C")
14002 Language = LinkageSpecDecl::lang_c;
14003 else if (Lang == "C++")
14004 Language = LinkageSpecDecl::lang_cxx;
14005 else if (Lang == "C++11")
14006 Language = LinkageSpecDecl::lang_cxx_11;
14007 else if (Lang == "C++14")
14008 Language = LinkageSpecDecl::lang_cxx_14;
14009 else {
14010 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
14011 << LangStr->getSourceRange();
14012 return nullptr;
14013 }
14014
14015 // FIXME: Add all the various semantics of linkage specifications
14016
14017 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
14018 LangStr->getExprLoc(), Language,
14019 LBraceLoc.isValid());
14020 CurContext->addDecl(D);
14021 PushDeclContext(S, D);
14022 return D;
14023}
14024
14025/// ActOnFinishLinkageSpecification - Complete the definition of
14026/// the C++ linkage specification LinkageSpec. If RBraceLoc is
14027/// valid, it's the position of the closing '}' brace in a linkage
14028/// specification that uses braces.
14029Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
14030 Decl *LinkageSpec,
14031 SourceLocation RBraceLoc) {
14032 if (RBraceLoc.isValid()) {
14033 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
14034 LSDecl->setRBraceLoc(RBraceLoc);
14035 }
14036 PopDeclContext();
14037 return LinkageSpec;
14038}
14039
14040Decl *Sema::ActOnEmptyDeclaration(Scope *S,
14041 const ParsedAttributesView &AttrList,
14042 SourceLocation SemiLoc) {
14043 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
14044 // Attribute declarations appertain to empty declaration so we handle
14045 // them here.
14046 ProcessDeclAttributeList(S, ED, AttrList);
14047
14048 CurContext->addDecl(ED);
14049 return ED;
14050}
14051
14052/// Perform semantic analysis for the variable declaration that
14053/// occurs within a C++ catch clause, returning the newly-created
14054/// variable.
14055VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
14056 TypeSourceInfo *TInfo,
14057 SourceLocation StartLoc,
14058 SourceLocation Loc,
14059 IdentifierInfo *Name) {
14060 bool Invalid = false;
14061 QualType ExDeclType = TInfo->getType();
14062
14063 // Arrays and functions decay.
14064 if (ExDeclType->isArrayType())
14065 ExDeclType = Context.getArrayDecayedType(ExDeclType);
14066 else if (ExDeclType->isFunctionType())
14067 ExDeclType = Context.getPointerType(ExDeclType);
14068
14069 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
14070 // The exception-declaration shall not denote a pointer or reference to an
14071 // incomplete type, other than [cv] void*.
14072 // N2844 forbids rvalue references.
14073 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
14074 Diag(Loc, diag::err_catch_rvalue_ref);
14075 Invalid = true;
14076 }
14077
14078 if (ExDeclType->isVariablyModifiedType()) {
14079 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
14080 Invalid = true;
14081 }
14082
14083 QualType BaseType = ExDeclType;
14084 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
14085 unsigned DK = diag::err_catch_incomplete;
14086 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
14087 BaseType = Ptr->getPointeeType();
14088 Mode = 1;
14089 DK = diag::err_catch_incomplete_ptr;
14090 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
14091 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
14092 BaseType = Ref->getPointeeType();
14093 Mode = 2;
14094 DK = diag::err_catch_incomplete_ref;
14095 }
14096 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
14097 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
14098 Invalid = true;
14099
14100 if (!Invalid && !ExDeclType->isDependentType() &&
14101 RequireNonAbstractType(Loc, ExDeclType,
14102 diag::err_abstract_type_in_decl,
14103 AbstractVariableType))
14104 Invalid = true;
14105
14106 // Only the non-fragile NeXT runtime currently supports C++ catches
14107 // of ObjC types, and no runtime supports catching ObjC types by value.
14108 if (!Invalid && getLangOpts().ObjC) {
14109 QualType T = ExDeclType;
14110 if (const ReferenceType *RT = T->getAs<ReferenceType>())
14111 T = RT->getPointeeType();
14112
14113 if (T->isObjCObjectType()) {
14114 Diag(Loc, diag::err_objc_object_catch);
14115 Invalid = true;
14116 } else if (T->isObjCObjectPointerType()) {
14117 // FIXME: should this be a test for macosx-fragile specifically?
14118 if (getLangOpts().ObjCRuntime.isFragile())
14119 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
14120 }
14121 }
14122
14123 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
14124 ExDeclType, TInfo, SC_None);
14125 ExDecl->setExceptionVariable(true);
14126
14127 // In ARC, infer 'retaining' for variables of retainable type.
14128 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
14129 Invalid = true;
14130
14131 if (!Invalid && !ExDeclType->isDependentType()) {
14132 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
14133 // Insulate this from anything else we might currently be parsing.
14134 EnterExpressionEvaluationContext scope(
14135 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14136
14137 // C++ [except.handle]p16:
14138 // The object declared in an exception-declaration or, if the
14139 // exception-declaration does not specify a name, a temporary (12.2) is
14140 // copy-initialized (8.5) from the exception object. [...]
14141 // The object is destroyed when the handler exits, after the destruction
14142 // of any automatic objects initialized within the handler.
14143 //
14144 // We just pretend to initialize the object with itself, then make sure
14145 // it can be destroyed later.
14146 QualType initType = Context.getExceptionObjectType(ExDeclType);
14147
14148 InitializedEntity entity =
14149 InitializedEntity::InitializeVariable(ExDecl);
14150 InitializationKind initKind =
14151 InitializationKind::CreateCopy(Loc, SourceLocation());
14152
14153 Expr *opaqueValue =
14154 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
14155 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
14156 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
14157 if (result.isInvalid())
14158 Invalid = true;
14159 else {
14160 // If the constructor used was non-trivial, set this as the
14161 // "initializer".
14162 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
14163 if (!construct->getConstructor()->isTrivial()) {
14164 Expr *init = MaybeCreateExprWithCleanups(construct);
14165 ExDecl->setInit(init);
14166 }
14167
14168 // And make sure it's destructable.
14169 FinalizeVarWithDestructor(ExDecl, recordType);
14170 }
14171 }
14172 }
14173
14174 if (Invalid)
14175 ExDecl->setInvalidDecl();
14176
14177 return ExDecl;
14178}
14179
14180/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
14181/// handler.
14182Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
14183 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14184 bool Invalid = D.isInvalidType();
14185
14186 // Check for unexpanded parameter packs.
14187 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14188 UPPC_ExceptionType)) {
14189 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
14190 D.getIdentifierLoc());
14191 Invalid = true;
14192 }
14193
14194 IdentifierInfo *II = D.getIdentifier();
14195 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
14196 LookupOrdinaryName,
14197 ForVisibleRedeclaration)) {
14198 // The scope should be freshly made just for us. There is just no way
14199 // it contains any previous declaration, except for function parameters in
14200 // a function-try-block's catch statement.
14201 assert(!S->isDeclScope(PrevDecl))((!S->isDeclScope(PrevDecl)) ? static_cast<void> (0)
: __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14201, __PRETTY_FUNCTION__))
;
14202 if (isDeclInScope(PrevDecl, CurContext, S)) {
14203 Diag(D.getIdentifierLoc(), diag::err_redefinition)
14204 << D.getIdentifier();
14205 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14206 Invalid = true;
14207 } else if (PrevDecl->isTemplateParameter())
14208 // Maybe we will complain about the shadowed template parameter.
14209 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14210 }
14211
14212 if (D.getCXXScopeSpec().isSet() && !Invalid) {
14213 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
14214 << D.getCXXScopeSpec().getRange();
14215 Invalid = true;
14216 }
14217
14218 VarDecl *ExDecl = BuildExceptionDeclaration(
14219 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
14220 if (Invalid)
14221 ExDecl->setInvalidDecl();
14222
14223 // Add the exception declaration into this scope.
14224 if (II)
14225 PushOnScopeChains(ExDecl, S);
14226 else
14227 CurContext->addDecl(ExDecl);
14228
14229 ProcessDeclAttributes(S, ExDecl, D);
14230 return ExDecl;
14231}
14232
14233Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14234 Expr *AssertExpr,
14235 Expr *AssertMessageExpr,
14236 SourceLocation RParenLoc) {
14237 StringLiteral *AssertMessage =
14238 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
14239
14240 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
14241 return nullptr;
14242
14243 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14244 AssertMessage, RParenLoc, false);
14245}
14246
14247Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14248 Expr *AssertExpr,
14249 StringLiteral *AssertMessage,
14250 SourceLocation RParenLoc,
14251 bool Failed) {
14252 assert(AssertExpr != nullptr && "Expected non-null condition")((AssertExpr != nullptr && "Expected non-null condition"
) ? static_cast<void> (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14252, __PRETTY_FUNCTION__))
;
14253 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14254 !Failed) {
14255 // In a static_assert-declaration, the constant-expression shall be a
14256 // constant expression that can be contextually converted to bool.
14257 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14258 if (Converted.isInvalid())
14259 Failed = true;
14260
14261 ExprResult FullAssertExpr =
14262 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
14263 /*DiscardedValue*/ false,
14264 /*IsConstexpr*/ true);
14265 if (FullAssertExpr.isInvalid())
14266 Failed = true;
14267 else
14268 AssertExpr = FullAssertExpr.get();
14269
14270 llvm::APSInt Cond;
14271 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
14272 diag::err_static_assert_expression_is_not_constant,
14273 /*AllowFold=*/false).isInvalid())
14274 Failed = true;
14275
14276 if (!Failed && !Cond) {
14277 SmallString<256> MsgBuffer;
14278 llvm::raw_svector_ostream Msg(MsgBuffer);
14279 if (AssertMessage)
14280 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14281
14282 Expr *InnerCond = nullptr;
14283 std::string InnerCondDescription;
14284 std::tie(InnerCond, InnerCondDescription) =
14285 findFailedBooleanCondition(Converted.get());
14286 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14287 && !isa<IntegerLiteral>(InnerCond)) {
14288 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14289 << InnerCondDescription << !AssertMessage
14290 << Msg.str() << InnerCond->getSourceRange();
14291 } else {
14292 Diag(StaticAssertLoc, diag::err_static_assert_failed)
14293 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14294 }
14295 Failed = true;
14296 }
14297 } else {
14298 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14299 /*DiscardedValue*/false,
14300 /*IsConstexpr*/true);
14301 if (FullAssertExpr.isInvalid())
14302 Failed = true;
14303 else
14304 AssertExpr = FullAssertExpr.get();
14305 }
14306
14307 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14308 AssertExpr, AssertMessage, RParenLoc,
14309 Failed);
14310
14311 CurContext->addDecl(Decl);
14312 return Decl;
14313}
14314
14315/// Perform semantic analysis of the given friend type declaration.
14316///
14317/// \returns A friend declaration that.
14318FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14319 SourceLocation FriendLoc,
14320 TypeSourceInfo *TSInfo) {
14321 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")((TSInfo && "NULL TypeSourceInfo for friend type declaration"
) ? static_cast<void> (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14321, __PRETTY_FUNCTION__))
;
14322
14323 QualType T = TSInfo->getType();
14324 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14325
14326 // C++03 [class.friend]p2:
14327 // An elaborated-type-specifier shall be used in a friend declaration
14328 // for a class.*
14329 //
14330 // * The class-key of the elaborated-type-specifier is required.
14331 if (!CodeSynthesisContexts.empty()) {
14332 // Do not complain about the form of friend template types during any kind
14333 // of code synthesis. For template instantiation, we will have complained
14334 // when the template was defined.
14335 } else {
14336 if (!T->isElaboratedTypeSpecifier()) {
14337 // If we evaluated the type to a record type, suggest putting
14338 // a tag in front.
14339 if (const RecordType *RT = T->getAs<RecordType>()) {
14340 RecordDecl *RD = RT->getDecl();
14341
14342 SmallString<16> InsertionText(" ");
14343 InsertionText += RD->getKindName();
14344
14345 Diag(TypeRange.getBegin(),
14346 getLangOpts().CPlusPlus11 ?
14347 diag::warn_cxx98_compat_unelaborated_friend_type :
14348 diag::ext_unelaborated_friend_type)
14349 << (unsigned) RD->getTagKind()
14350 << T
14351 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14352 InsertionText);
14353 } else {
14354 Diag(FriendLoc,
14355 getLangOpts().CPlusPlus11 ?
14356 diag::warn_cxx98_compat_nonclass_type_friend :
14357 diag::ext_nonclass_type_friend)
14358 << T
14359 << TypeRange;
14360 }
14361 } else if (T->getAs<EnumType>()) {
14362 Diag(FriendLoc,
14363 getLangOpts().CPlusPlus11 ?
14364 diag::warn_cxx98_compat_enum_friend :
14365 diag::ext_enum_friend)
14366 << T
14367 << TypeRange;
14368 }
14369
14370 // C++11 [class.friend]p3:
14371 // A friend declaration that does not declare a function shall have one
14372 // of the following forms:
14373 // friend elaborated-type-specifier ;
14374 // friend simple-type-specifier ;
14375 // friend typename-specifier ;
14376 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14377 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14378 }
14379
14380 // If the type specifier in a friend declaration designates a (possibly
14381 // cv-qualified) class type, that class is declared as a friend; otherwise,
14382 // the friend declaration is ignored.
14383 return FriendDecl::Create(Context, CurContext,
14384 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14385 FriendLoc);
14386}
14387
14388/// Handle a friend tag declaration where the scope specifier was
14389/// templated.
14390Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14391 unsigned TagSpec, SourceLocation TagLoc,
14392 CXXScopeSpec &SS, IdentifierInfo *Name,
14393 SourceLocation NameLoc,
14394 const ParsedAttributesView &Attr,
14395 MultiTemplateParamsArg TempParamLists) {
14396 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14397
14398 bool IsMemberSpecialization = false;
14399 bool Invalid = false;
14400
14401 if (TemplateParameterList *TemplateParams =
14402 MatchTemplateParametersToScopeSpecifier(
14403 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14404 IsMemberSpecialization, Invalid)) {
14405 if (TemplateParams->size() > 0) {
14406 // This is a declaration of a class template.
14407 if (Invalid)
14408 return nullptr;
14409
14410 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14411 NameLoc, Attr, TemplateParams, AS_public,
14412 /*ModulePrivateLoc=*/SourceLocation(),
14413 FriendLoc, TempParamLists.size() - 1,
14414 TempParamLists.data()).get();
14415 } else {
14416 // The "template<>" header is extraneous.
14417 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14418 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14419 IsMemberSpecialization = true;
14420 }
14421 }
14422
14423 if (Invalid) return nullptr;
14424
14425 bool isAllExplicitSpecializations = true;
14426 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14427 if (TempParamLists[I]->size()) {
14428 isAllExplicitSpecializations = false;
14429 break;
14430 }
14431 }
14432
14433 // FIXME: don't ignore attributes.
14434
14435 // If it's explicit specializations all the way down, just forget
14436 // about the template header and build an appropriate non-templated
14437 // friend. TODO: for source fidelity, remember the headers.
14438 if (isAllExplicitSpecializations) {
14439 if (SS.isEmpty()) {
14440 bool Owned = false;
14441 bool IsDependent = false;
14442 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14443 Attr, AS_public,
14444 /*ModulePrivateLoc=*/SourceLocation(),
14445 MultiTemplateParamsArg(), Owned, IsDependent,
14446 /*ScopedEnumKWLoc=*/SourceLocation(),
14447 /*ScopedEnumUsesClassTag=*/false,
14448 /*UnderlyingType=*/TypeResult(),
14449 /*IsTypeSpecifier=*/false,
14450 /*IsTemplateParamOrArg=*/false);
14451 }
14452
14453 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14454 ElaboratedTypeKeyword Keyword
14455 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14456 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14457 *Name, NameLoc);
14458 if (T.isNull())
14459 return nullptr;
14460
14461 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14462 if (isa<DependentNameType>(T)) {
14463 DependentNameTypeLoc TL =
14464 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14465 TL.setElaboratedKeywordLoc(TagLoc);
14466 TL.setQualifierLoc(QualifierLoc);
14467 TL.setNameLoc(NameLoc);
14468 } else {
14469 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14470 TL.setElaboratedKeywordLoc(TagLoc);
14471 TL.setQualifierLoc(QualifierLoc);
14472 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14473 }
14474
14475 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14476 TSI, FriendLoc, TempParamLists);
14477 Friend->setAccess(AS_public);
14478 CurContext->addDecl(Friend);
14479 return Friend;
14480 }
14481
14482 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")((SS.isNotEmpty() && "valid templated tag with no SS and no direct?"
) ? static_cast<void> (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14482, __PRETTY_FUNCTION__))
;
14483
14484
14485
14486 // Handle the case of a templated-scope friend class. e.g.
14487 // template <class T> class A<T>::B;
14488 // FIXME: we don't support these right now.
14489 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14490 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14491 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14492 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14493 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14494 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14495 TL.setElaboratedKeywordLoc(TagLoc);
14496 TL.setQualifierLoc(SS.getWithLocInContext(Context));
14497 TL.setNameLoc(NameLoc);
14498
14499 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14500 TSI, FriendLoc, TempParamLists);
14501 Friend->setAccess(AS_public);
14502 Friend->setUnsupportedFriend(true);
14503 CurContext->addDecl(Friend);
14504 return Friend;
14505}
14506
14507/// Handle a friend type declaration. This works in tandem with
14508/// ActOnTag.
14509///
14510/// Notes on friend class templates:
14511///
14512/// We generally treat friend class declarations as if they were
14513/// declaring a class. So, for example, the elaborated type specifier
14514/// in a friend declaration is required to obey the restrictions of a
14515/// class-head (i.e. no typedefs in the scope chain), template
14516/// parameters are required to match up with simple template-ids, &c.
14517/// However, unlike when declaring a template specialization, it's
14518/// okay to refer to a template specialization without an empty
14519/// template parameter declaration, e.g.
14520/// friend class A<T>::B<unsigned>;
14521/// We permit this as a special case; if there are any template
14522/// parameters present at all, require proper matching, i.e.
14523/// template <> template \<class T> friend class A<int>::B;
14524Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14525 MultiTemplateParamsArg TempParams) {
14526 SourceLocation Loc = DS.getBeginLoc();
14527
14528 assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14528, __PRETTY_FUNCTION__))
;
14529 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast
<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14529, __PRETTY_FUNCTION__))
;
14530
14531 // C++ [class.friend]p3:
14532 // A friend declaration that does not declare a function shall have one of
14533 // the following forms:
14534 // friend elaborated-type-specifier ;
14535 // friend simple-type-specifier ;
14536 // friend typename-specifier ;
14537 //
14538 // Any declaration with a type qualifier does not have that form. (It's
14539 // legal to specify a qualified type as a friend, you just can't write the
14540 // keywords.)
14541 if (DS.getTypeQualifiers()) {
14542 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14543 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14544 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14545 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14546 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14547 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14548 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14549 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14550 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14551 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14552 }
14553
14554 // Try to convert the decl specifier to a type. This works for
14555 // friend templates because ActOnTag never produces a ClassTemplateDecl
14556 // for a TUK_Friend.
14557 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14558 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14559 QualType T = TSI->getType();
14560 if (TheDeclarator.isInvalidType())
14561 return nullptr;
14562
14563 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14564 return nullptr;
14565
14566 // This is definitely an error in C++98. It's probably meant to
14567 // be forbidden in C++0x, too, but the specification is just
14568 // poorly written.
14569 //
14570 // The problem is with declarations like the following:
14571 // template <T> friend A<T>::foo;
14572 // where deciding whether a class C is a friend or not now hinges
14573 // on whether there exists an instantiation of A that causes
14574 // 'foo' to equal C. There are restrictions on class-heads
14575 // (which we declare (by fiat) elaborated friend declarations to
14576 // be) that makes this tractable.
14577 //
14578 // FIXME: handle "template <> friend class A<T>;", which
14579 // is possibly well-formed? Who even knows?
14580 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14581 Diag(Loc, diag::err_tagless_friend_type_template)
14582 << DS.getSourceRange();
14583 return nullptr;
14584 }
14585
14586 // C++98 [class.friend]p1: A friend of a class is a function
14587 // or class that is not a member of the class . . .
14588 // This is fixed in DR77, which just barely didn't make the C++03
14589 // deadline. It's also a very silly restriction that seriously
14590 // affects inner classes and which nobody else seems to implement;
14591 // thus we never diagnose it, not even in -pedantic.
14592 //
14593 // But note that we could warn about it: it's always useless to
14594 // friend one of your own members (it's not, however, worthless to
14595 // friend a member of an arbitrary specialization of your template).
14596
14597 Decl *D;
14598 if (!TempParams.empty())
14599 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14600 TempParams,
14601 TSI,
14602 DS.getFriendSpecLoc());
14603 else
14604 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14605
14606 if (!D)
14607 return nullptr;
14608
14609 D->setAccess(AS_public);
14610 CurContext->addDecl(D);
14611
14612 return D;
14613}
14614
14615NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14616 MultiTemplateParamsArg TemplateParams) {
14617 const DeclSpec &DS = D.getDeclSpec();
14618
14619 assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14619, __PRETTY_FUNCTION__))
;
14620 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast
<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14620, __PRETTY_FUNCTION__))
;
14621
14622 SourceLocation Loc = D.getIdentifierLoc();
14623 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14624
14625 // C++ [class.friend]p1
14626 // A friend of a class is a function or class....
14627 // Note that this sees through typedefs, which is intended.
14628 // It *doesn't* see through dependent types, which is correct
14629 // according to [temp.arg.type]p3:
14630 // If a declaration acquires a function type through a
14631 // type dependent on a template-parameter and this causes
14632 // a declaration that does not use the syntactic form of a
14633 // function declarator to have a function type, the program
14634 // is ill-formed.
14635 if (!TInfo->getType()->isFunctionType()) {
14636 Diag(Loc, diag::err_unexpected_friend);
14637
14638 // It might be worthwhile to try to recover by creating an
14639 // appropriate declaration.
14640 return nullptr;
14641 }
14642
14643 // C++ [namespace.memdef]p3
14644 // - If a friend declaration in a non-local class first declares a
14645 // class or function, the friend class or function is a member
14646 // of the innermost enclosing namespace.
14647 // - The name of the friend is not found by simple name lookup
14648 // until a matching declaration is provided in that namespace
14649 // scope (either before or after the class declaration granting
14650 // friendship).
14651 // - If a friend function is called, its name may be found by the
14652 // name lookup that considers functions from namespaces and
14653 // classes associated with the types of the function arguments.
14654 // - When looking for a prior declaration of a class or a function
14655 // declared as a friend, scopes outside the innermost enclosing
14656 // namespace scope are not considered.
14657
14658 CXXScopeSpec &SS = D.getCXXScopeSpec();
14659 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14660 assert(NameInfo.getName())((NameInfo.getName()) ? static_cast<void> (0) : __assert_fail
("NameInfo.getName()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14660, __PRETTY_FUNCTION__))
;
14661
14662 // Check for unexpanded parameter packs.
14663 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14664 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14665 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14666 return nullptr;
14667
14668 // The context we found the declaration in, or in which we should
14669 // create the declaration.
14670 DeclContext *DC;
14671 Scope *DCScope = S;
14672 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14673 ForExternalRedeclaration);
14674
14675 // There are five cases here.
14676 // - There's no scope specifier and we're in a local class. Only look
14677 // for functions declared in the immediately-enclosing block scope.
14678 // We recover from invalid scope qualifiers as if they just weren't there.
14679 FunctionDecl *FunctionContainingLocalClass = nullptr;
14680 if ((SS.isInvalid() || !SS.isSet()) &&
14681 (FunctionContainingLocalClass =
14682 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14683 // C++11 [class.friend]p11:
14684 // If a friend declaration appears in a local class and the name
14685 // specified is an unqualified name, a prior declaration is
14686 // looked up without considering scopes that are outside the
14687 // innermost enclosing non-class scope. For a friend function
14688 // declaration, if there is no prior declaration, the program is
14689 // ill-formed.
14690
14691 // Find the innermost enclosing non-class scope. This is the block
14692 // scope containing the local class definition (or for a nested class,
14693 // the outer local class).
14694 DCScope = S->getFnParent();
14695
14696 // Look up the function name in the scope.
14697 Previous.clear(LookupLocalFriendName);
14698 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14699
14700 if (!Previous.empty()) {
14701 // All possible previous declarations must have the same context:
14702 // either they were declared at block scope or they are members of
14703 // one of the enclosing local classes.
14704 DC = Previous.getRepresentativeDecl()->getDeclContext();
14705 } else {
14706 // This is ill-formed, but provide the context that we would have
14707 // declared the function in, if we were permitted to, for error recovery.
14708 DC = FunctionContainingLocalClass;
14709 }
14710 adjustContextForLocalExternDecl(DC);
14711
14712 // C++ [class.friend]p6:
14713 // A function can be defined in a friend declaration of a class if and
14714 // only if the class is a non-local class (9.8), the function name is
14715 // unqualified, and the function has namespace scope.
14716 if (D.isFunctionDefinition()) {
14717 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14718 }
14719
14720 // - There's no scope specifier, in which case we just go to the
14721 // appropriate scope and look for a function or function template
14722 // there as appropriate.
14723 } else if (SS.isInvalid() || !SS.isSet()) {
14724 // C++11 [namespace.memdef]p3:
14725 // If the name in a friend declaration is neither qualified nor
14726 // a template-id and the declaration is a function or an
14727 // elaborated-type-specifier, the lookup to determine whether
14728 // the entity has been previously declared shall not consider
14729 // any scopes outside the innermost enclosing namespace.
14730 bool isTemplateId =
14731 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14732
14733 // Find the appropriate context according to the above.
14734 DC = CurContext;
14735
14736 // Skip class contexts. If someone can cite chapter and verse
14737 // for this behavior, that would be nice --- it's what GCC and
14738 // EDG do, and it seems like a reasonable intent, but the spec
14739 // really only says that checks for unqualified existing
14740 // declarations should stop at the nearest enclosing namespace,
14741 // not that they should only consider the nearest enclosing
14742 // namespace.
14743 while (DC->isRecord())
14744 DC = DC->getParent();
14745
14746 DeclContext *LookupDC = DC;
14747 while (LookupDC->isTransparentContext())
14748 LookupDC = LookupDC->getParent();
14749
14750 while (true) {
14751 LookupQualifiedName(Previous, LookupDC);
14752
14753 if (!Previous.empty()) {
14754 DC = LookupDC;
14755 break;
14756 }
14757
14758 if (isTemplateId) {
14759 if (isa<TranslationUnitDecl>(LookupDC)) break;
14760 } else {
14761 if (LookupDC->isFileContext()) break;
14762 }
14763 LookupDC = LookupDC->getParent();
14764 }
14765
14766 DCScope = getScopeForDeclContext(S, DC);
14767
14768 // - There's a non-dependent scope specifier, in which case we
14769 // compute it and do a previous lookup there for a function
14770 // or function template.
14771 } else if (!SS.getScopeRep()->isDependent()) {
14772 DC = computeDeclContext(SS);
14773 if (!DC) return nullptr;
14774
14775 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14776
14777 LookupQualifiedName(Previous, DC);
14778
14779 // C++ [class.friend]p1: A friend of a class is a function or
14780 // class that is not a member of the class . . .
14781 if (DC->Equals(CurContext))
14782 Diag(DS.getFriendSpecLoc(),
14783 getLangOpts().CPlusPlus11 ?
14784 diag::warn_cxx98_compat_friend_is_member :
14785 diag::err_friend_is_member);
14786
14787 if (D.isFunctionDefinition()) {
14788 // C++ [class.friend]p6:
14789 // A function can be defined in a friend declaration of a class if and
14790 // only if the class is a non-local class (9.8), the function name is
14791 // unqualified, and the function has namespace scope.
14792 //
14793 // FIXME: We should only do this if the scope specifier names the
14794 // innermost enclosing namespace; otherwise the fixit changes the
14795 // meaning of the code.
14796 SemaDiagnosticBuilder DB
14797 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14798
14799 DB << SS.getScopeRep();
14800 if (DC->isFileContext())
14801 DB << FixItHint::CreateRemoval(SS.getRange());
14802 SS.clear();
14803 }
14804
14805 // - There's a scope specifier that does not match any template
14806 // parameter lists, in which case we use some arbitrary context,
14807 // create a method or method template, and wait for instantiation.
14808 // - There's a scope specifier that does match some template
14809 // parameter lists, which we don't handle right now.
14810 } else {
14811 if (D.isFunctionDefinition()) {
14812 // C++ [class.friend]p6:
14813 // A function can be defined in a friend declaration of a class if and
14814 // only if the class is a non-local class (9.8), the function name is
14815 // unqualified, and the function has namespace scope.
14816 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14817 << SS.getScopeRep();
14818 }
14819
14820 DC = CurContext;
14821 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")((isa<CXXRecordDecl>(DC) && "friend declaration not in class?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14821, __PRETTY_FUNCTION__))
;
14822 }
14823
14824 if (!DC->isRecord()) {
14825 int DiagArg = -1;
14826 switch (D.getName().getKind()) {
14827 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14828 case UnqualifiedIdKind::IK_ConstructorName:
14829 DiagArg = 0;
14830 break;
14831 case UnqualifiedIdKind::IK_DestructorName:
14832 DiagArg = 1;
14833 break;
14834 case UnqualifiedIdKind::IK_ConversionFunctionId:
14835 DiagArg = 2;
14836 break;
14837 case UnqualifiedIdKind::IK_DeductionGuideName:
14838 DiagArg = 3;
14839 break;
14840 case UnqualifiedIdKind::IK_Identifier:
14841 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14842 case UnqualifiedIdKind::IK_LiteralOperatorId:
14843 case UnqualifiedIdKind::IK_OperatorFunctionId:
14844 case UnqualifiedIdKind::IK_TemplateId:
14845 break;
14846 }
14847 // This implies that it has to be an operator or function.
14848 if (DiagArg >= 0) {
14849 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14850 return nullptr;
14851 }
14852 }
14853
14854 // FIXME: This is an egregious hack to cope with cases where the scope stack
14855 // does not contain the declaration context, i.e., in an out-of-line
14856 // definition of a class.
14857 Scope FakeDCScope(S, Scope::DeclScope, Diags);
14858 if (!DCScope) {
14859 FakeDCScope.setEntity(DC);
14860 DCScope = &FakeDCScope;
14861 }
14862
14863 bool AddToScope = true;
14864 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14865 TemplateParams, AddToScope);
14866 if (!ND) return nullptr;
14867
14868 assert(ND->getLexicalDeclContext() == CurContext)((ND->getLexicalDeclContext() == CurContext) ? static_cast
<void> (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 14868, __PRETTY_FUNCTION__))
;
14869
14870 // If we performed typo correction, we might have added a scope specifier
14871 // and changed the decl context.
14872 DC = ND->getDeclContext();
14873
14874 // Add the function declaration to the appropriate lookup tables,
14875 // adjusting the redeclarations list as necessary. We don't
14876 // want to do this yet if the friending class is dependent.
14877 //
14878 // Also update the scope-based lookup if the target context's
14879 // lookup context is in lexical scope.
14880 if (!CurContext->isDependentContext()) {
14881 DC = DC->getRedeclContext();
14882 DC->makeDeclVisibleInContext(ND);
14883 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14884 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14885 }
14886
14887 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14888 D.getIdentifierLoc(), ND,
14889 DS.getFriendSpecLoc());
14890 FrD->setAccess(AS_public);
14891 CurContext->addDecl(FrD);
14892
14893 if (ND->isInvalidDecl()) {
14894 FrD->setInvalidDecl();
14895 } else {
14896 if (DC->isRecord()) CheckFriendAccess(ND);
14897
14898 FunctionDecl *FD;
14899 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14900 FD = FTD->getTemplatedDecl();
14901 else
14902 FD = cast<FunctionDecl>(ND);
14903
14904 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14905 // default argument expression, that declaration shall be a definition
14906 // and shall be the only declaration of the function or function
14907 // template in the translation unit.
14908 if (functionDeclHasDefaultArgument(FD)) {
14909 // We can't look at FD->getPreviousDecl() because it may not have been set
14910 // if we're in a dependent context. If the function is known to be a
14911 // redeclaration, we will have narrowed Previous down to the right decl.
14912 if (D.isRedeclaration()) {
14913 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14914 Diag(Previous.getRepresentativeDecl()->getLocation(),
14915 diag::note_previous_declaration);
14916 } else if (!D.isFunctionDefinition())
14917 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14918 }
14919
14920 // Mark templated-scope function declarations as unsupported.
14921 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14922 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14923 << SS.getScopeRep() << SS.getRange()
14924 << cast<CXXRecordDecl>(CurContext);
14925 FrD->setUnsupportedFriend(true);
14926 }
14927 }
14928
14929 return ND;
14930}
14931
14932void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14933 AdjustDeclIfTemplate(Dcl);
14934
14935 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14936 if (!Fn) {
14937 Diag(DelLoc, diag::err_deleted_non_function);
14938 return;
14939 }
14940
14941 // Deleted function does not have a body.
14942 Fn->setWillHaveBody(false);
14943
14944 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14945 // Don't consider the implicit declaration we generate for explicit
14946 // specializations. FIXME: Do not generate these implicit declarations.
14947 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14948 Prev->getPreviousDecl()) &&
14949 !Prev->isDefined()) {
14950 Diag(DelLoc, diag::err_deleted_decl_not_first);
14951 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14952 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14953 : diag::note_previous_declaration);
14954 }
14955 // If the declaration wasn't the first, we delete the function anyway for
14956 // recovery.
14957 Fn = Fn->getCanonicalDecl();
14958 }
14959
14960 // dllimport/dllexport cannot be deleted.
14961 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14962 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14963 Fn->setInvalidDecl();
14964 }
14965
14966 if (Fn->isDeleted())
14967 return;
14968
14969 // See if we're deleting a function which is already known to override a
14970 // non-deleted virtual function.
14971 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14972 bool IssuedDiagnostic = false;
14973 for (const CXXMethodDecl *O : MD->overridden_methods()) {
14974 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14975 if (!IssuedDiagnostic) {
14976 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14977 IssuedDiagnostic = true;
14978 }
14979 Diag(O->getLocation(), diag::note_overridden_virtual_function);
14980 }
14981 }
14982 // If this function was implicitly deleted because it was defaulted,
14983 // explain why it was deleted.
14984 if (IssuedDiagnostic && MD->isDefaulted())
14985 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14986 /*Diagnose*/true);
14987 }
14988
14989 // C++11 [basic.start.main]p3:
14990 // A program that defines main as deleted [...] is ill-formed.
14991 if (Fn->isMain())
14992 Diag(DelLoc, diag::err_deleted_main);
14993
14994 // C++11 [dcl.fct.def.delete]p4:
14995 // A deleted function is implicitly inline.
14996 Fn->setImplicitlyInline();
14997 Fn->setDeletedAsWritten();
14998}
14999
15000void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
15001 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
15002
15003 if (MD) {
15004 if (MD->getParent()->isDependentType()) {
15005 MD->setDefaulted();
15006 MD->setExplicitlyDefaulted();
15007 return;
15008 }
15009
15010 CXXSpecialMember Member = getSpecialMember(MD);
15011 if (Member == CXXInvalid) {
15012 if (!MD->isInvalidDecl())
15013 Diag(DefaultLoc, diag::err_default_special_members);
15014 return;
15015 }
15016
15017 MD->setDefaulted();
15018 MD->setExplicitlyDefaulted();
15019
15020 // Unset that we will have a body for this function. We might not,
15021 // if it turns out to be trivial, and we don't need this marking now
15022 // that we've marked it as defaulted.
15023 MD->setWillHaveBody(false);
15024
15025 // If this definition appears within the record, do the checking when
15026 // the record is complete.
15027 const FunctionDecl *Primary = MD;
15028 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
15029 // Ask the template instantiation pattern that actually had the
15030 // '= default' on it.
15031 Primary = Pattern;
15032
15033 // If the method was defaulted on its first declaration, we will have
15034 // already performed the checking in CheckCompletedCXXClass. Such a
15035 // declaration doesn't trigger an implicit definition.
15036 if (Primary->getCanonicalDecl()->isDefaulted())
15037 return;
15038
15039 CheckExplicitlyDefaultedSpecialMember(MD);
15040
15041 if (!MD->isInvalidDecl())
15042 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
15043 } else {
15044 Diag(DefaultLoc, diag::err_default_special_members);
15045 }
15046}
15047
15048static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
15049 for (Stmt *SubStmt : S->children()) {
15050 if (!SubStmt)
15051 continue;
15052 if (isa<ReturnStmt>(SubStmt))
15053 Self.Diag(SubStmt->getBeginLoc(),
15054 diag::err_return_in_constructor_handler);
15055 if (!isa<Expr>(SubStmt))
15056 SearchForReturnInStmt(Self, SubStmt);
15057 }
15058}
15059
15060void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
15061 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
15062 CXXCatchStmt *Handler = TryBlock->getHandler(I);
15063 SearchForReturnInStmt(*this, Handler);
15064 }
15065}
15066
15067bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
15068 const CXXMethodDecl *Old) {
15069 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
15070 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
15071
15072 if (OldFT->hasExtParameterInfos()) {
15073 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
15074 // A parameter of the overriding method should be annotated with noescape
15075 // if the corresponding parameter of the overridden method is annotated.
15076 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
15077 !NewFT->getExtParameterInfo(I).isNoEscape()) {
15078 Diag(New->getParamDecl(I)->getLocation(),
15079 diag::warn_overriding_method_missing_noescape);
15080 Diag(Old->getParamDecl(I)->getLocation(),
15081 diag::note_overridden_marked_noescape);
15082 }
15083 }
15084
15085 // Virtual overrides must have the same code_seg.
15086 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
15087 const auto *NewCSA = New->getAttr<CodeSegAttr>();
15088 if ((NewCSA || OldCSA) &&
15089 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
15090 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
15091 Diag(Old->getLocation(), diag::note_previous_declaration);
15092 return true;
15093 }
15094
15095 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
15096
15097 // If the calling conventions match, everything is fine
15098 if (NewCC == OldCC)
15099 return false;
15100
15101 // If the calling conventions mismatch because the new function is static,
15102 // suppress the calling convention mismatch error; the error about static
15103 // function override (err_static_overrides_virtual from
15104 // Sema::CheckFunctionDeclaration) is more clear.
15105 if (New->getStorageClass() == SC_Static)
15106 return false;
15107
15108 Diag(New->getLocation(),
15109 diag::err_conflicting_overriding_cc_attributes)
15110 << New->getDeclName() << New->getType() << Old->getType();
15111 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
15112 return true;
15113}
15114
15115bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
15116 const CXXMethodDecl *Old) {
15117 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
15118 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
15119
15120 if (Context.hasSameType(NewTy, OldTy) ||
15121 NewTy->isDependentType() || OldTy->isDependentType())
15122 return false;
15123
15124 // Check if the return types are covariant
15125 QualType NewClassTy, OldClassTy;
15126
15127 /// Both types must be pointers or references to classes.
15128 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
15129 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
15130 NewClassTy = NewPT->getPointeeType();
15131 OldClassTy = OldPT->getPointeeType();
15132 }
15133 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
15134 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
15135 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
15136 NewClassTy = NewRT->getPointeeType();
15137 OldClassTy = OldRT->getPointeeType();
15138 }
15139 }
15140 }
15141
15142 // The return types aren't either both pointers or references to a class type.
15143 if (NewClassTy.isNull()) {
15144 Diag(New->getLocation(),
15145 diag::err_different_return_type_for_overriding_virtual_function)
15146 << New->getDeclName() << NewTy << OldTy
15147 << New->getReturnTypeSourceRange();
15148 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15149 << Old->getReturnTypeSourceRange();
15150
15151 return true;
15152 }
15153
15154 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
15155 // C++14 [class.virtual]p8:
15156 // If the class type in the covariant return type of D::f differs from
15157 // that of B::f, the class type in the return type of D::f shall be
15158 // complete at the point of declaration of D::f or shall be the class
15159 // type D.
15160 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
15161 if (!RT->isBeingDefined() &&
15162 RequireCompleteType(New->getLocation(), NewClassTy,
15163 diag::err_covariant_return_incomplete,
15164 New->getDeclName()))
15165 return true;
15166 }
15167
15168 // Check if the new class derives from the old class.
15169 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
15170 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
15171 << New->getDeclName() << NewTy << OldTy
15172 << New->getReturnTypeSourceRange();
15173 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15174 << Old->getReturnTypeSourceRange();
15175 return true;
15176 }
15177
15178 // Check if we the conversion from derived to base is valid.
15179 if (CheckDerivedToBaseConversion(
15180 NewClassTy, OldClassTy,
15181 diag::err_covariant_return_inaccessible_base,
15182 diag::err_covariant_return_ambiguous_derived_to_base_conv,
15183 New->getLocation(), New->getReturnTypeSourceRange(),
15184 New->getDeclName(), nullptr)) {
15185 // FIXME: this note won't trigger for delayed access control
15186 // diagnostics, and it's impossible to get an undelayed error
15187 // here from access control during the original parse because
15188 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
15189 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15190 << Old->getReturnTypeSourceRange();
15191 return true;
15192 }
15193 }
15194
15195 // The qualifiers of the return types must be the same.
15196 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
15197 Diag(New->getLocation(),
15198 diag::err_covariant_return_type_different_qualifications)
15199 << New->getDeclName() << NewTy << OldTy
15200 << New->getReturnTypeSourceRange();
15201 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15202 << Old->getReturnTypeSourceRange();
15203 return true;
15204 }
15205
15206
15207 // The new class type must have the same or less qualifiers as the old type.
15208 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
15209 Diag(New->getLocation(),
15210 diag::err_covariant_return_type_class_type_more_qualified)
15211 << New->getDeclName() << NewTy << OldTy
15212 << New->getReturnTypeSourceRange();
15213 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15214 << Old->getReturnTypeSourceRange();
15215 return true;
15216 }
15217
15218 return false;
15219}
15220
15221/// Mark the given method pure.
15222///
15223/// \param Method the method to be marked pure.
15224///
15225/// \param InitRange the source range that covers the "0" initializer.
15226bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
15227 SourceLocation EndLoc = InitRange.getEnd();
15228 if (EndLoc.isValid())
15229 Method->setRangeEnd(EndLoc);
15230
15231 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
15232 Method->setPure();
15233 return false;
15234 }
15235
15236 if (!Method->isInvalidDecl())
15237 Diag(Method->getLocation(), diag::err_non_virtual_pure)
15238 << Method->getDeclName() << InitRange;
15239 return true;
15240}
15241
15242void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
15243 if (D->getFriendObjectKind())
15244 Diag(D->getLocation(), diag::err_pure_friend);
15245 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
15246 CheckPureMethod(M, ZeroLoc);
15247 else
15248 Diag(D->getLocation(), diag::err_illegal_initializer);
15249}
15250
15251/// Determine whether the given declaration is a global variable or
15252/// static data member.
15253static bool isNonlocalVariable(const Decl *D) {
15254 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15255 return Var->hasGlobalStorage();
15256
15257 return false;
15258}
15259
15260/// Invoked when we are about to parse an initializer for the declaration
15261/// 'Dcl'.
15262///
15263/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15264/// static data member of class X, names should be looked up in the scope of
15265/// class X. If the declaration had a scope specifier, a scope will have
15266/// been created and passed in for this purpose. Otherwise, S will be null.
15267void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15268 // If there is no declaration, there was an error parsing it.
15269 if (!D || D->isInvalidDecl())
15270 return;
15271
15272 // We will always have a nested name specifier here, but this declaration
15273 // might not be out of line if the specifier names the current namespace:
15274 // extern int n;
15275 // int ::n = 0;
15276 if (S && D->isOutOfLine())
15277 EnterDeclaratorContext(S, D->getDeclContext());
15278
15279 // If we are parsing the initializer for a static data member, push a
15280 // new expression evaluation context that is associated with this static
15281 // data member.
15282 if (isNonlocalVariable(D))
15283 PushExpressionEvaluationContext(
15284 ExpressionEvaluationContext::PotentiallyEvaluated, D);
15285}
15286
15287/// Invoked after we are finished parsing an initializer for the declaration D.
15288void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15289 // If there is no declaration, there was an error parsing it.
15290 if (!D || D->isInvalidDecl())
15291 return;
15292
15293 if (isNonlocalVariable(D))
15294 PopExpressionEvaluationContext();
15295
15296 if (S && D->isOutOfLine())
15297 ExitDeclaratorContext(S);
15298}
15299
15300/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15301/// C++ if/switch/while/for statement.
15302/// e.g: "if (int x = f()) {...}"
15303DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15304 // C++ 6.4p2:
15305 // The declarator shall not specify a function or an array.
15306 // The type-specifier-seq shall not contain typedef and shall not declare a
15307 // new class or enumeration.
15308 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class of condition decl."
) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15309, __PRETTY_FUNCTION__))
15309 "Parser allowed 'typedef' as storage class of condition decl.")((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class of condition decl."
) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15309, __PRETTY_FUNCTION__))
;
15310
15311 Decl *Dcl = ActOnDeclarator(S, D);
15312 if (!Dcl)
15313 return true;
15314
15315 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15316 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15317 << D.getSourceRange();
15318 return true;
15319 }
15320
15321 return Dcl;
15322}
15323
15324void Sema::LoadExternalVTableUses() {
15325 if (!ExternalSource)
15326 return;
15327
15328 SmallVector<ExternalVTableUse, 4> VTables;
15329 ExternalSource->ReadUsedVTables(VTables);
15330 SmallVector<VTableUse, 4> NewUses;
15331 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15332 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15333 = VTablesUsed.find(VTables[I].Record);
15334 // Even if a definition wasn't required before, it may be required now.
15335 if (Pos != VTablesUsed.end()) {
15336 if (!Pos->second && VTables[I].DefinitionRequired)
15337 Pos->second = true;
15338 continue;
15339 }
15340
15341 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15342 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15343 }
15344
15345 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15346}
15347
15348void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15349 bool DefinitionRequired) {
15350 // Ignore any vtable uses in unevaluated operands or for classes that do
15351 // not have a vtable.
15352 if (!Class->isDynamicClass() || Class->isDependentContext() ||
15353 CurContext->isDependentContext() || isUnevaluatedContext())
15354 return;
15355 // Do not mark as used if compiling for the device outside of the target
15356 // region.
15357 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15358 !isInOpenMPDeclareTargetContext() &&
15359 !isInOpenMPTargetExecutionDirective()) {
15360 if (!DefinitionRequired)
15361 MarkVirtualMembersReferenced(Loc, Class);
15362 return;
15363 }
15364
15365 // Try to insert this class into the map.
15366 LoadExternalVTableUses();
15367 Class = Class->getCanonicalDecl();
15368 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15369 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15370 if (!Pos.second) {
15371 // If we already had an entry, check to see if we are promoting this vtable
15372 // to require a definition. If so, we need to reappend to the VTableUses
15373 // list, since we may have already processed the first entry.
15374 if (DefinitionRequired && !Pos.first->second) {
15375 Pos.first->second = true;
15376 } else {
15377 // Otherwise, we can early exit.
15378 return;
15379 }
15380 } else {
15381 // The Microsoft ABI requires that we perform the destructor body
15382 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15383 // the deleting destructor is emitted with the vtable, not with the
15384 // destructor definition as in the Itanium ABI.
15385 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15386 CXXDestructorDecl *DD = Class->getDestructor();
15387 if (DD && DD->isVirtual() && !DD->isDeleted()) {
15388 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15389 // If this is an out-of-line declaration, marking it referenced will
15390 // not do anything. Manually call CheckDestructor to look up operator
15391 // delete().
15392 ContextRAII SavedContext(*this, DD);
15393 CheckDestructor(DD);
15394 } else {
15395 MarkFunctionReferenced(Loc, Class->getDestructor());
15396 }
15397 }
15398 }
15399 }
15400
15401 // Local classes need to have their virtual members marked
15402 // immediately. For all other classes, we mark their virtual members
15403 // at the end of the translation unit.
15404 if (Class->isLocalClass())
15405 MarkVirtualMembersReferenced(Loc, Class);
15406 else
15407 VTableUses.push_back(std::make_pair(Class, Loc));
15408}
15409
15410bool Sema::DefineUsedVTables() {
15411 LoadExternalVTableUses();
15412 if (VTableUses.empty())
15413 return false;
15414
15415 // Note: The VTableUses vector could grow as a result of marking
15416 // the members of a class as "used", so we check the size each
15417 // time through the loop and prefer indices (which are stable) to
15418 // iterators (which are not).
15419 bool DefinedAnything = false;
15420 for (unsigned I = 0; I != VTableUses.size(); ++I) {
15421 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15422 if (!Class)
15423 continue;
15424 TemplateSpecializationKind ClassTSK =
15425 Class->getTemplateSpecializationKind();
15426
15427 SourceLocation Loc = VTableUses[I].second;
15428
15429 bool DefineVTable = true;
15430
15431 // If this class has a key function, but that key function is
15432 // defined in another translation unit, we don't need to emit the
15433 // vtable even though we're using it.
15434 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15435 if (KeyFunction && !KeyFunction->hasBody()) {
15436 // The key function is in another translation unit.
15437 DefineVTable = false;
15438 TemplateSpecializationKind TSK =
15439 KeyFunction->getTemplateSpecializationKind();
15440 assert(TSK != TSK_ExplicitInstantiationDefinition &&((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15442, __PRETTY_FUNCTION__))
15441 TSK != TSK_ImplicitInstantiation &&((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15442, __PRETTY_FUNCTION__))
15442 "Instantiations don't have key functions")((TSK != TSK_ExplicitInstantiationDefinition && TSK !=
TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15442, __PRETTY_FUNCTION__))
;
15443 (void)TSK;
15444 } else if (!KeyFunction) {
15445 // If we have a class with no key function that is the subject
15446 // of an explicit instantiation declaration, suppress the
15447 // vtable; it will live with the explicit instantiation
15448 // definition.
15449 bool IsExplicitInstantiationDeclaration =
15450 ClassTSK == TSK_ExplicitInstantiationDeclaration;
15451 for (auto R : Class->redecls()) {
15452 TemplateSpecializationKind TSK
15453 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15454 if (TSK == TSK_ExplicitInstantiationDeclaration)
15455 IsExplicitInstantiationDeclaration = true;
15456 else if (TSK == TSK_ExplicitInstantiationDefinition) {
15457 IsExplicitInstantiationDeclaration = false;
15458 break;
15459 }
15460 }
15461
15462 if (IsExplicitInstantiationDeclaration)
15463 DefineVTable = false;
15464 }
15465
15466 // The exception specifications for all virtual members may be needed even
15467 // if we are not providing an authoritative form of the vtable in this TU.
15468 // We may choose to emit it available_externally anyway.
15469 if (!DefineVTable) {
15470 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15471 continue;
15472 }
15473
15474 // Mark all of the virtual members of this class as referenced, so
15475 // that we can build a vtable. Then, tell the AST consumer that a
15476 // vtable for this class is required.
15477 DefinedAnything = true;
15478 MarkVirtualMembersReferenced(Loc, Class);
15479 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15480 if (VTablesUsed[Canonical])
15481 Consumer.HandleVTable(Class);
15482
15483 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15484 // no key function or the key function is inlined. Don't warn in C++ ABIs
15485 // that lack key functions, since the user won't be able to make one.
15486 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15487 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15488 const FunctionDecl *KeyFunctionDef = nullptr;
15489 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15490 KeyFunctionDef->isInlined())) {
15491 Diag(Class->getLocation(),
15492 ClassTSK == TSK_ExplicitInstantiationDefinition
15493 ? diag::warn_weak_template_vtable
15494 : diag::warn_weak_vtable)
15495 << Class;
15496 }
15497 }
15498 }
15499 VTableUses.clear();
15500
15501 return DefinedAnything;
15502}
15503
15504void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15505 const CXXRecordDecl *RD) {
15506 for (const auto *I : RD->methods())
15507 if (I->isVirtual() && !I->isPure())
15508 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15509}
15510
15511void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15512 const CXXRecordDecl *RD,
15513 bool ConstexprOnly) {
15514 // Mark all functions which will appear in RD's vtable as used.
15515 CXXFinalOverriderMap FinalOverriders;
15516 RD->getFinalOverriders(FinalOverriders);
15517 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15518 E = FinalOverriders.end();
15519 I != E; ++I) {
15520 for (OverridingMethods::const_iterator OI = I->second.begin(),
15521 OE = I->second.end();
15522 OI != OE; ++OI) {
15523 assert(OI->second.size() > 0 && "no final overrider")((OI->second.size() > 0 && "no final overrider"
) ? static_cast<void> (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15523, __PRETTY_FUNCTION__))
;
15524 CXXMethodDecl *Overrider = OI->second.front().Method;
15525
15526 // C++ [basic.def.odr]p2:
15527 // [...] A virtual member function is used if it is not pure. [...]
15528 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15529 MarkFunctionReferenced(Loc, Overrider);
15530 }
15531 }
15532
15533 // Only classes that have virtual bases need a VTT.
15534 if (RD->getNumVBases() == 0)
15535 return;
15536
15537 for (const auto &I : RD->bases()) {
15538 const CXXRecordDecl *Base =
15539 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15540 if (Base->getNumVBases() == 0)
15541 continue;
15542 MarkVirtualMembersReferenced(Loc, Base);
15543 }
15544}
15545
15546/// SetIvarInitializers - This routine builds initialization ASTs for the
15547/// Objective-C implementation whose ivars need be initialized.
15548void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15549 if (!getLangOpts().CPlusPlus)
15550 return;
15551 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15552 SmallVector<ObjCIvarDecl*, 8> ivars;
15553 CollectIvarsToConstructOrDestruct(OID, ivars);
15554 if (ivars.empty())
15555 return;
15556 SmallVector<CXXCtorInitializer*, 32> AllToInit;
15557 for (unsigned i = 0; i < ivars.size(); i++) {
15558 FieldDecl *Field = ivars[i];
15559 if (Field->isInvalidDecl())
15560 continue;
15561
15562 CXXCtorInitializer *Member;
15563 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15564 InitializationKind InitKind =
15565 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15566
15567 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15568 ExprResult MemberInit =
15569 InitSeq.Perform(*this, InitEntity, InitKind, None);
15570 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15571 // Note, MemberInit could actually come back empty if no initialization
15572 // is required (e.g., because it would call a trivial default constructor)
15573 if (!MemberInit.get() || MemberInit.isInvalid())
15574 continue;
15575
15576 Member =
15577 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15578 SourceLocation(),
15579 MemberInit.getAs<Expr>(),
15580 SourceLocation());
15581 AllToInit.push_back(Member);
15582
15583 // Be sure that the destructor is accessible and is marked as referenced.
15584 if (const RecordType *RecordTy =
15585 Context.getBaseElementType(Field->getType())
15586 ->getAs<RecordType>()) {
15587 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15588 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15589 MarkFunctionReferenced(Field->getLocation(), Destructor);
15590 CheckDestructorAccess(Field->getLocation(), Destructor,
15591 PDiag(diag::err_access_dtor_ivar)
15592 << Context.getBaseElementType(Field->getType()));
15593 }
15594 }
15595 }
15596 ObjCImplementation->setIvarInitializers(Context,
15597 AllToInit.data(), AllToInit.size());
15598 }
15599}
15600
15601static
15602void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15603 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15604 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15605 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15606 Sema &S) {
15607 if (Ctor->isInvalidDecl())
15608 return;
15609
15610 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15611
15612 // Target may not be determinable yet, for instance if this is a dependent
15613 // call in an uninstantiated template.
15614 if (Target) {
15615 const FunctionDecl *FNTarget = nullptr;
15616 (void)Target->hasBody(FNTarget);
15617 Target = const_cast<CXXConstructorDecl*>(
15618 cast_or_null<CXXConstructorDecl>(FNTarget));
15619 }
15620
15621 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15622 // Avoid dereferencing a null pointer here.
15623 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15624
15625 if (!Current.insert(Canonical).second)
15626 return;
15627
15628 // We know that beyond here, we aren't chaining into a cycle.
15629 if (!Target || !Target->isDelegatingConstructor() ||
15630 Target->isInvalidDecl() || Valid.count(TCanonical)) {
15631 Valid.insert(Current.begin(), Current.end());
15632 Current.clear();
15633 // We've hit a cycle.
15634 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15635 Current.count(TCanonical)) {
15636 // If we haven't diagnosed this cycle yet, do so now.
15637 if (!Invalid.count(TCanonical)) {
15638 S.Diag((*Ctor->init_begin())->getSourceLocation(),
15639 diag::warn_delegating_ctor_cycle)
15640 << Ctor;
15641
15642 // Don't add a note for a function delegating directly to itself.
15643 if (TCanonical != Canonical)
15644 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15645
15646 CXXConstructorDecl *C = Target;
15647 while (C->getCanonicalDecl() != Canonical) {
15648 const FunctionDecl *FNTarget = nullptr;
15649 (void)C->getTargetConstructor()->hasBody(FNTarget);
15650 assert(FNTarget && "Ctor cycle through bodiless function")((FNTarget && "Ctor cycle through bodiless function")
? static_cast<void> (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15650, __PRETTY_FUNCTION__))
;
15651
15652 C = const_cast<CXXConstructorDecl*>(
15653 cast<CXXConstructorDecl>(FNTarget));
15654 S.Diag(C->getLocation(), diag::note_which_delegates_to);
15655 }
15656 }
15657
15658 Invalid.insert(Current.begin(), Current.end());
15659 Current.clear();
15660 } else {
15661 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15662 }
15663}
15664
15665
15666void Sema::CheckDelegatingCtorCycles() {
15667 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15668
15669 for (DelegatingCtorDeclsType::iterator
15670 I = DelegatingCtorDecls.begin(ExternalSource),
15671 E = DelegatingCtorDecls.end();
15672 I != E; ++I)
15673 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15674
15675 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15676 (*CI)->setInvalidDecl();
15677}
15678
15679namespace {
15680 /// AST visitor that finds references to the 'this' expression.
15681 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15682 Sema &S;
15683
15684 public:
15685 explicit FindCXXThisExpr(Sema &S) : S(S) { }
15686
15687 bool VisitCXXThisExpr(CXXThisExpr *E) {
15688 S.Diag(E->getLocation(), diag::err_this_static_member_func)
15689 << E->isImplicit();
15690 return false;
15691 }
15692 };
15693}
15694
15695bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15696 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15697 if (!TSInfo)
15698 return false;
15699
15700 TypeLoc TL = TSInfo->getTypeLoc();
15701 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15702 if (!ProtoTL)
15703 return false;
15704
15705 // C++11 [expr.prim.general]p3:
15706 // [The expression this] shall not appear before the optional
15707 // cv-qualifier-seq and it shall not appear within the declaration of a
15708 // static member function (although its type and value category are defined
15709 // within a static member function as they are within a non-static member
15710 // function). [ Note: this is because declaration matching does not occur
15711 // until the complete declarator is known. - end note ]
15712 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15713 FindCXXThisExpr Finder(*this);
15714
15715 // If the return type came after the cv-qualifier-seq, check it now.
15716 if (Proto->hasTrailingReturn() &&
15717 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15718 return true;
15719
15720 // Check the exception specification.
15721 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15722 return true;
15723
15724 return checkThisInStaticMemberFunctionAttributes(Method);
15725}
15726
15727bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15728 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15729 if (!TSInfo)
15730 return false;
15731
15732 TypeLoc TL = TSInfo->getTypeLoc();
15733 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15734 if (!ProtoTL)
15735 return false;
15736
15737 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15738 FindCXXThisExpr Finder(*this);
15739
15740 switch (Proto->getExceptionSpecType()) {
15741 case EST_Unparsed:
15742 case EST_Uninstantiated:
15743 case EST_Unevaluated:
15744 case EST_BasicNoexcept:
15745 case EST_NoThrow:
15746 case EST_DynamicNone:
15747 case EST_MSAny:
15748 case EST_None:
15749 break;
15750
15751 case EST_DependentNoexcept:
15752 case EST_NoexceptFalse:
15753 case EST_NoexceptTrue:
15754 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15755 return true;
15756 LLVM_FALLTHROUGH[[gnu::fallthrough]];
15757
15758 case EST_Dynamic:
15759 for (const auto &E : Proto->exceptions()) {
15760 if (!Finder.TraverseType(E))
15761 return true;
15762 }
15763 break;
15764 }
15765
15766 return false;
15767}
15768
15769bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15770 FindCXXThisExpr Finder(*this);
15771
15772 // Check attributes.
15773 for (const auto *A : Method->attrs()) {
15774 // FIXME: This should be emitted by tblgen.
15775 Expr *Arg = nullptr;
15776 ArrayRef<Expr *> Args;
15777 if (const auto *G = dyn_cast<GuardedByAttr>(A))
15778 Arg = G->getArg();
15779 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15780 Arg = G->getArg();
15781 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15782 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15783 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15784 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15785 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15786 Arg = ETLF->getSuccessValue();
15787 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15788 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15789 Arg = STLF->getSuccessValue();
15790 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15791 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15792 Arg = LR->getArg();
15793 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15794 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15795 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15796 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15797 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15798 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15799 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15800 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15801 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15802 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15803
15804 if (Arg && !Finder.TraverseStmt(Arg))
15805 return true;
15806
15807 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15808 if (!Finder.TraverseStmt(Args[I]))
15809 return true;
15810 }
15811 }
15812
15813 return false;
15814}
15815
15816void Sema::checkExceptionSpecification(
15817 bool IsTopLevel, ExceptionSpecificationType EST,
15818 ArrayRef<ParsedType> DynamicExceptions,
15819 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15820 SmallVectorImpl<QualType> &Exceptions,
15821 FunctionProtoType::ExceptionSpecInfo &ESI) {
15822 Exceptions.clear();
15823 ESI.Type = EST;
15824 if (EST == EST_Dynamic) {
15825 Exceptions.reserve(DynamicExceptions.size());
15826 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15827 // FIXME: Preserve type source info.
15828 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15829
15830 if (IsTopLevel) {
15831 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15832 collectUnexpandedParameterPacks(ET, Unexpanded);
15833 if (!Unexpanded.empty()) {
15834 DiagnoseUnexpandedParameterPacks(
15835 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15836 Unexpanded);
15837 continue;
15838 }
15839 }
15840
15841 // Check that the type is valid for an exception spec, and
15842 // drop it if not.
15843 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15844 Exceptions.push_back(ET);
15845 }
15846 ESI.Exceptions = Exceptions;
15847 return;
15848 }
15849
15850 if (isComputedNoexcept(EST)) {
15851 assert((NoexceptExpr->isTypeDependent() ||(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15854, __PRETTY_FUNCTION__))
15852 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15854, __PRETTY_FUNCTION__))
15853 Context.BoolTy) &&(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15854, __PRETTY_FUNCTION__))
15854 "Parser should have made sure that the expression is boolean")(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType
()->getCanonicalTypeUnqualified() == Context.BoolTy) &&
"Parser should have made sure that the expression is boolean"
) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp"
, 15854, __PRETTY_FUNCTION__))
;
15855 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15856 ESI.Type = EST_BasicNoexcept;
15857 return;
15858 }
15859
15860 ESI.NoexceptExpr = NoexceptExpr;
15861 return;
15862 }
15863}
15864
15865void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15866 ExceptionSpecificationType EST,
15867 SourceRange SpecificationRange,
15868 ArrayRef<ParsedType> DynamicExceptions,
15869 ArrayRef<SourceRange> DynamicExceptionRanges,
15870 Expr *NoexceptExpr) {
15871 if (!MethodD)
15872 return;
15873
15874 // Dig out the method we're referring to.
15875 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15876 MethodD = FunTmpl->getTemplatedDecl();
15877
15878 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15879 if (!Method)
15880 return;
15881
15882 // Check the exception specification.
15883 llvm::SmallVector<QualType, 4> Exceptions;
15884 FunctionProtoType::ExceptionSpecInfo ESI;
15885 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15886 DynamicExceptionRanges, NoexceptExpr, Exceptions,
15887 ESI);
15888
15889 // Update the exception specification on the function type.
15890 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15891
15892 if (Method->isStatic())
15893 checkThisInStaticMemberFunctionExceptionSpec(Method);
15894
15895 if (Method->isVirtual()) {
15896 // Check overrides, which we previously had to delay.
15897 for (const CXXMethodDecl *O : Method->overridden_methods())
15898 CheckOverridingFunctionExceptionSpec(Method, O);
15899 }
15900}
15901
15902/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15903///
15904MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15905 SourceLocation DeclStart, Declarator &D,
15906 Expr *BitWidth,
15907 InClassInitStyle InitStyle,
15908 AccessSpecifier AS,
15909 const ParsedAttr &MSPropertyAttr) {
15910 IdentifierInfo *II = D.getIdentifier();
15911 if (!II) {
15912 Diag(DeclStart, diag::err_anonymous_property);
15913 return nullptr;
15914 }
15915 SourceLocation Loc = D.getIdentifierLoc();
15916
15917 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15918 QualType T = TInfo->getType();
15919 if (getLangOpts().CPlusPlus) {
15920 CheckExtraCXXDefaultArguments(D);
15921
15922 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15923 UPPC_DataMemberType)) {
15924 D.setInvalidType();
15925 T = Context.IntTy;
15926 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15927 }
15928 }
15929
15930 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15931
15932 if (D.getDeclSpec().isInlineSpecified())
15933 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15934 << getLangOpts().CPlusPlus17;
15935 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15936 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15937 diag::err_invalid_thread)
15938 << DeclSpec::getSpecifierName(TSCS);
15939
15940 // Check to see if this name was declared as a member previously
15941 NamedDecl *PrevDecl = nullptr;
15942 LookupResult Previous(*this, II, Loc, LookupMemberName,
15943 ForVisibleRedeclaration);
15944 LookupName(Previous, S);
15945 switch (Previous.getResultKind()) {
15946 case LookupResult::Found:
15947 case LookupResult::FoundUnresolvedValue:
15948 PrevDecl = Previous.getAsSingle<NamedDecl>();
15949 break;
15950
15951 case LookupResult::FoundOverloaded:
15952 PrevDecl = Previous.getRepresentativeDecl();
15953 break;
15954
15955 case LookupResult::NotFound:
15956 case LookupResult::NotFoundInCurrentInstantiation:
15957 case LookupResult::Ambiguous:
15958 break;
15959 }
15960
15961 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15962 // Maybe we will complain about the shadowed template parameter.
15963 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15964 // Just pretend that we didn't see the previous declaration.
15965 PrevDecl = nullptr;
15966 }
15967
15968 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15969 PrevDecl = nullptr;
15970
15971 SourceLocation TSSL = D.getBeginLoc();
15972 MSPropertyDecl *NewPD =
15973 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15974 MSPropertyAttr.getPropertyDataGetter(),
15975 MSPropertyAttr.getPropertyDataSetter());
15976 ProcessDeclAttributes(TUScope, NewPD, D);
15977 NewPD->setAccess(AS);
15978
15979 if (NewPD->isInvalidDecl())
15980 Record->setInvalidDecl();
15981
15982 if (D.getDeclSpec().isModulePrivateSpecified())
15983 NewPD->setModulePrivate();
15984
15985 if (NewPD->isInvalidDecl() && PrevDecl) {
15986 // Don't introduce NewFD into scope; there's already something
15987 // with the same name in the same scope.
15988 } else if (II) {
15989 PushOnScopeChains(NewPD, S);
15990 } else
15991 Record->addDecl(NewPD);
15992
15993 return NewPD;
15994}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Decl.h

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

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.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/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.
1447 class TypeBitfields {
1448 friend class Type;
1449 template <class T> friend class TypePropertyCache;
1450
1451 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 unsigned TC : 8;
1453
1454 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1455 unsigned Dependent : 1;
1456
1457 /// Whether this type somehow involves a template parameter, even
1458 /// if the resolution of the type does not depend on a template parameter.
1459 unsigned InstantiationDependent : 1;
1460
1461 /// Whether this type is a variably-modified type (C99 6.7.5).
1462 unsigned VariablyModified : 1;
1463
1464 /// Whether this type contains an unexpanded parameter pack
1465 /// (for C++11 variadic templates).
1466 unsigned ContainsUnexpandedParameterPack : 1;
1467
1468 /// True if the cache (i.e. the bitfields here starting with
1469 /// 'Cache') is valid.
1470 mutable unsigned CacheValid : 1;
1471
1472 /// Linkage of this type.
1473 mutable unsigned CachedLinkage : 3;
1474
1475 /// Whether this type involves and local or unnamed types.
1476 mutable unsigned CachedLocalOrUnnamed : 1;
1477
1478 /// Whether this type comes from an AST file.
1479 mutable unsigned FromAST : 1;
1480
1481 bool isCacheValid() const {
1482 return CacheValid;
1483 }
1484
1485 Linkage getLinkage() const {
1486 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1486, __PRETTY_FUNCTION__))
;
1487 return static_cast<Linkage>(CachedLinkage);
1488 }
1489
1490 bool hasLocalOrUnnamedType() const {
1491 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 return CachedLocalOrUnnamed;
1493 }
1494 };
1495 enum { NumTypeBits = 18 };
1496
1497protected:
1498 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 // into Type.
1500
1501 class ArrayTypeBitfields {
1502 friend class ArrayType;
1503
1504 unsigned : NumTypeBits;
1505
1506 /// CVR qualifiers from declarations like
1507 /// 'int X[static restrict 4]'. For function parameters only.
1508 unsigned IndexTypeQuals : 3;
1509
1510 /// Storage class qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 /// Actually an ArrayType::ArraySizeModifier.
1513 unsigned SizeModifier : 3;
1514 };
1515
1516 class BuiltinTypeBitfields {
1517 friend class BuiltinType;
1518
1519 unsigned : NumTypeBits;
1520
1521 /// The kind (BuiltinType::Kind) of builtin type this is.
1522 unsigned Kind : 8;
1523 };
1524
1525 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1526 /// Only common bits are stored here. Additional uncommon bits are stored
1527 /// in a trailing object after FunctionProtoType.
1528 class FunctionTypeBitfields {
1529 friend class FunctionProtoType;
1530 friend class FunctionType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// Extra information which affects how the function is called, like
1535 /// regparm and the calling convention.
1536 unsigned ExtInfo : 12;
1537
1538 /// The ref-qualifier associated with a \c FunctionProtoType.
1539 ///
1540 /// This is a value of type \c RefQualifierKind.
1541 unsigned RefQualifier : 2;
1542
1543 /// Used only by FunctionProtoType, put here to pack with the
1544 /// other bitfields.
1545 /// The qualifiers are part of FunctionProtoType because...
1546 ///
1547 /// C++ 8.3.5p4: The return type, the parameter type list and the
1548 /// cv-qualifier-seq, [...], are part of the function type.
1549 unsigned FastTypeQuals : Qualifiers::FastWidth;
1550 /// Whether this function has extended Qualifiers.
1551 unsigned HasExtQuals : 1;
1552
1553 /// The number of parameters this function has, not counting '...'.
1554 /// According to [implimits] 8 bits should be enough here but this is
1555 /// somewhat easy to exceed with metaprogramming and so we would like to
1556 /// keep NumParams as wide as reasonably possible.
1557 unsigned NumParams : 16;
1558
1559 /// The type of exception specification this function has.
1560 unsigned ExceptionSpecType : 4;
1561
1562 /// Whether this function has extended parameter information.
1563 unsigned HasExtParameterInfos : 1;
1564
1565 /// Whether the function is variadic.
1566 unsigned Variadic : 1;
1567
1568 /// Whether this function has a trailing return type.
1569 unsigned HasTrailingReturn : 1;
1570 };
1571
1572 class ObjCObjectTypeBitfields {
1573 friend class ObjCObjectType;
1574
1575 unsigned : NumTypeBits;
1576
1577 /// The number of type arguments stored directly on this object type.
1578 unsigned NumTypeArgs : 7;
1579
1580 /// The number of protocols stored directly on this object type.
1581 unsigned NumProtocols : 6;
1582
1583 /// Whether this is a "kindof" type.
1584 unsigned IsKindOf : 1;
1585 };
1586
1587 class ReferenceTypeBitfields {
1588 friend class ReferenceType;
1589
1590 unsigned : NumTypeBits;
1591
1592 /// True if the type was originally spelled with an lvalue sigil.
1593 /// This is never true of rvalue references but can also be false
1594 /// on lvalue references because of C++0x [dcl.typedef]p9,
1595 /// as follows:
1596 ///
1597 /// typedef int &ref; // lvalue, spelled lvalue
1598 /// typedef int &&rvref; // rvalue
1599 /// ref &a; // lvalue, inner ref, spelled lvalue
1600 /// ref &&a; // lvalue, inner ref
1601 /// rvref &a; // lvalue, inner ref, spelled lvalue
1602 /// rvref &&a; // rvalue, inner ref
1603 unsigned SpelledAsLValue : 1;
1604
1605 /// True if the inner type is a reference type. This only happens
1606 /// in non-canonical forms.
1607 unsigned InnerRef : 1;
1608 };
1609
1610 class TypeWithKeywordBitfields {
1611 friend class TypeWithKeyword;
1612
1613 unsigned : NumTypeBits;
1614
1615 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1616 unsigned Keyword : 8;
1617 };
1618
1619 enum { NumTypeWithKeywordBits = 8 };
1620
1621 class ElaboratedTypeBitfields {
1622 friend class ElaboratedType;
1623
1624 unsigned : NumTypeBits;
1625 unsigned : NumTypeWithKeywordBits;
1626
1627 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1628 unsigned HasOwnedTagDecl : 1;
1629 };
1630
1631 class VectorTypeBitfields {
1632 friend class VectorType;
1633 friend class DependentVectorType;
1634
1635 unsigned : NumTypeBits;
1636
1637 /// The kind of vector, either a generic vector type or some
1638 /// target-specific vector type such as for AltiVec or Neon.
1639 unsigned VecKind : 3;
1640
1641 /// The number of elements in the vector.
1642 unsigned NumElements : 29 - NumTypeBits;
1643
1644 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1645 };
1646
1647 class AttributedTypeBitfields {
1648 friend class AttributedType;
1649
1650 unsigned : NumTypeBits;
1651
1652 /// An AttributedType::Kind
1653 unsigned AttrKind : 32 - NumTypeBits;
1654 };
1655
1656 class AutoTypeBitfields {
1657 friend class AutoType;
1658
1659 unsigned : NumTypeBits;
1660
1661 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1662 /// or '__auto_type'? AutoTypeKeyword value.
1663 unsigned Keyword : 2;
1664 };
1665
1666 class SubstTemplateTypeParmPackTypeBitfields {
1667 friend class SubstTemplateTypeParmPackType;
1668
1669 unsigned : NumTypeBits;
1670
1671 /// The number of template arguments in \c Arguments, which is
1672 /// expected to be able to hold at least 1024 according to [implimits].
1673 /// However as this limit is somewhat easy to hit with template
1674 /// metaprogramming we'd prefer to keep it as large as possible.
1675 /// At the moment it has been left as a non-bitfield since this type
1676 /// safely fits in 64 bits as an unsigned, so there is no reason to
1677 /// introduce the performance impact of a bitfield.
1678 unsigned NumArgs;
1679 };
1680
1681 class TemplateSpecializationTypeBitfields {
1682 friend class TemplateSpecializationType;
1683
1684 unsigned : NumTypeBits;
1685
1686 /// Whether this template specialization type is a substituted type alias.
1687 unsigned TypeAlias : 1;
1688
1689 /// The number of template arguments named in this class template
1690 /// specialization, which is expected to be able to hold at least 1024
1691 /// according to [implimits]. However, as this limit is somewhat easy to
1692 /// hit with template metaprogramming we'd prefer to keep it as large
1693 /// as possible. At the moment it has been left as a non-bitfield since
1694 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1695 /// to introduce the performance impact of a bitfield.
1696 unsigned NumArgs;
1697 };
1698
1699 class DependentTemplateSpecializationTypeBitfields {
1700 friend class DependentTemplateSpecializationType;
1701
1702 unsigned : NumTypeBits;
1703 unsigned : NumTypeWithKeywordBits;
1704
1705 /// The number of template arguments named in this class template
1706 /// specialization, which is expected to be able to hold at least 1024
1707 /// according to [implimits]. However, as this limit is somewhat easy to
1708 /// hit with template metaprogramming we'd prefer to keep it as large
1709 /// as possible. At the moment it has been left as a non-bitfield since
1710 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1711 /// to introduce the performance impact of a bitfield.
1712 unsigned NumArgs;
1713 };
1714
1715 class PackExpansionTypeBitfields {
1716 friend class PackExpansionType;
1717
1718 unsigned : NumTypeBits;
1719
1720 /// The number of expansions that this pack expansion will
1721 /// generate when substituted (+1), which is expected to be able to
1722 /// hold at least 1024 according to [implimits]. However, as this limit
1723 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1724 /// keep it as large as possible. At the moment it has been left as a
1725 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1726 /// there is no reason to introduce the performance impact of a bitfield.
1727 ///
1728 /// This field will only have a non-zero value when some of the parameter
1729 /// packs that occur within the pattern have been substituted but others
1730 /// have not.
1731 unsigned NumExpansions;
1732 };
1733
1734 union {
1735 TypeBitfields TypeBits;
1736 ArrayTypeBitfields ArrayTypeBits;
1737 AttributedTypeBitfields AttributedTypeBits;
1738 AutoTypeBitfields AutoTypeBits;
1739 BuiltinTypeBitfields BuiltinTypeBits;
1740 FunctionTypeBitfields FunctionTypeBits;
1741 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1742 ReferenceTypeBitfields ReferenceTypeBits;
1743 TypeWithKeywordBitfields TypeWithKeywordBits;
1744 ElaboratedTypeBitfields ElaboratedTypeBits;
1745 VectorTypeBitfields VectorTypeBits;
1746 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1747 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1748 DependentTemplateSpecializationTypeBitfields
1749 DependentTemplateSpecializationTypeBits;
1750 PackExpansionTypeBitfields PackExpansionTypeBits;
1751
1752 static_assert(sizeof(TypeBitfields) <= 8,
1753 "TypeBitfields is larger than 8 bytes!");
1754 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1755 "ArrayTypeBitfields is larger than 8 bytes!");
1756 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1757 "AttributedTypeBitfields is larger than 8 bytes!");
1758 static_assert(sizeof(AutoTypeBitfields) <= 8,
1759 "AutoTypeBitfields is larger than 8 bytes!");
1760 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1761 "BuiltinTypeBitfields is larger than 8 bytes!");
1762 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1763 "FunctionTypeBitfields is larger than 8 bytes!");
1764 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1765 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1767 "ReferenceTypeBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1769 "TypeWithKeywordBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1771 "ElaboratedTypeBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(VectorTypeBitfields) <= 8,
1773 "VectorTypeBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1775 "SubstTemplateTypeParmPackTypeBitfields is larger"
1776 " than 8 bytes!");
1777 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1778 "TemplateSpecializationTypeBitfields is larger"
1779 " than 8 bytes!");
1780 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1781 "DependentTemplateSpecializationTypeBitfields is larger"
1782 " than 8 bytes!");
1783 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1784 "PackExpansionTypeBitfields is larger than 8 bytes");
1785 };
1786
1787private:
1788 template <class T> friend class TypePropertyCache;
1789
1790 /// Set whether this type comes from an AST file.
1791 void setFromAST(bool V = true) const {
1792 TypeBits.FromAST = V;
1793 }
1794
1795protected:
1796 friend class ASTContext;
1797
1798 Type(TypeClass tc, QualType canon, bool Dependent,
1799 bool InstantiationDependent, bool VariablyModified,
1800 bool ContainsUnexpandedParameterPack)
1801 : ExtQualsTypeCommonBase(this,
1802 canon.isNull() ? QualType(this_(), 0) : canon) {
1803 TypeBits.TC = tc;
1804 TypeBits.Dependent = Dependent;
1805 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1806 TypeBits.VariablyModified = VariablyModified;
1807 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1808 TypeBits.CacheValid = false;
1809 TypeBits.CachedLocalOrUnnamed = false;
1810 TypeBits.CachedLinkage = NoLinkage;
1811 TypeBits.FromAST = false;
1812 }
1813
1814 // silence VC++ warning C4355: 'this' : used in base member initializer list
1815 Type *this_() { return this; }
1816
1817 void setDependent(bool D = true) {
1818 TypeBits.Dependent = D;
1819 if (D)
1820 TypeBits.InstantiationDependent = true;
1821 }
1822
1823 void setInstantiationDependent(bool D = true) {
1824 TypeBits.InstantiationDependent = D; }
1825
1826 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1827
1828 void setContainsUnexpandedParameterPack(bool PP = true) {
1829 TypeBits.ContainsUnexpandedParameterPack = PP;
1830 }
1831
1832public:
1833 friend class ASTReader;
1834 friend class ASTWriter;
1835
1836 Type(const Type &) = delete;
1837 Type(Type &&) = delete;
1838 Type &operator=(const Type &) = delete;
1839 Type &operator=(Type &&) = delete;
1840
1841 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1842
1843 /// Whether this type comes from an AST file.
1844 bool isFromAST() const { return TypeBits.FromAST; }
1845
1846 /// Whether this type is or contains an unexpanded parameter
1847 /// pack, used to support C++0x variadic templates.
1848 ///
1849 /// A type that contains a parameter pack shall be expanded by the
1850 /// ellipsis operator at some point. For example, the typedef in the
1851 /// following example contains an unexpanded parameter pack 'T':
1852 ///
1853 /// \code
1854 /// template<typename ...T>
1855 /// struct X {
1856 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1857 /// };
1858 /// \endcode
1859 ///
1860 /// Note that this routine does not specify which
1861 bool containsUnexpandedParameterPack() const {
1862 return TypeBits.ContainsUnexpandedParameterPack;
1863 }
1864
1865 /// Determines if this type would be canonical if it had no further
1866 /// qualification.
1867 bool isCanonicalUnqualified() const {
1868 return CanonicalType == QualType(this, 0);
1869 }
1870
1871 /// Pull a single level of sugar off of this locally-unqualified type.
1872 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1873 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1874 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1875
1876 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1877 /// object types, function types, and incomplete types.
1878
1879 /// Return true if this is an incomplete type.
1880 /// A type that can describe objects, but which lacks information needed to
1881 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1882 /// routine will need to determine if the size is actually required.
1883 ///
1884 /// Def If non-null, and the type refers to some kind of declaration
1885 /// that can be completed (such as a C struct, C++ class, or Objective-C
1886 /// class), will be set to the declaration.
1887 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1888
1889 /// Return true if this is an incomplete or object
1890 /// type, in other words, not a function type.
1891 bool isIncompleteOrObjectType() const {
1892 return !isFunctionType();
1893 }
1894
1895 /// Determine whether this type is an object type.
1896 bool isObjectType() const {
1897 // C++ [basic.types]p8:
1898 // An object type is a (possibly cv-qualified) type that is not a
1899 // function type, not a reference type, and not a void type.
1900 return !isReferenceType() && !isFunctionType() && !isVoidType();
1901 }
1902
1903 /// Return true if this is a literal type
1904 /// (C++11 [basic.types]p10)
1905 bool isLiteralType(const ASTContext &Ctx) const;
1906
1907 /// Test if this type is a standard-layout type.
1908 /// (C++0x [basic.type]p9)
1909 bool isStandardLayoutType() const;
1910
1911 /// Helper methods to distinguish type categories. All type predicates
1912 /// operate on the canonical type, ignoring typedefs and qualifiers.
1913
1914 /// Returns true if the type is a builtin type.
1915 bool isBuiltinType() const;
1916
1917 /// Test for a particular builtin type.
1918 bool isSpecificBuiltinType(unsigned K) const;
1919
1920 /// Test for a type which does not represent an actual type-system type but
1921 /// is instead used as a placeholder for various convenient purposes within
1922 /// Clang. All such types are BuiltinTypes.
1923 bool isPlaceholderType() const;
1924 const BuiltinType *getAsPlaceholderType() const;
1925
1926 /// Test for a specific placeholder type.
1927 bool isSpecificPlaceholderType(unsigned K) const;
1928
1929 /// Test for a placeholder type other than Overload; see
1930 /// BuiltinType::isNonOverloadPlaceholderType.
1931 bool isNonOverloadPlaceholderType() const;
1932
1933 /// isIntegerType() does *not* include complex integers (a GCC extension).
1934 /// isComplexIntegerType() can be used to test for complex integers.
1935 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1936 bool isEnumeralType() const;
1937
1938 /// Determine whether this type is a scoped enumeration type.
1939 bool isScopedEnumeralType() const;
1940 bool isBooleanType() const;
1941 bool isCharType() const;
1942 bool isWideCharType() const;
1943 bool isChar8Type() const;
1944 bool isChar16Type() const;
1945 bool isChar32Type() const;
1946 bool isAnyCharacterType() const;
1947 bool isIntegralType(const ASTContext &Ctx) const;
1948
1949 /// Determine whether this type is an integral or enumeration type.
1950 bool isIntegralOrEnumerationType() const;
1951
1952 /// Determine whether this type is an integral or unscoped enumeration type.
1953 bool isIntegralOrUnscopedEnumerationType() const;
1954
1955 /// Floating point categories.
1956 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1957 /// isComplexType() does *not* include complex integers (a GCC extension).
1958 /// isComplexIntegerType() can be used to test for complex integers.
1959 bool isComplexType() const; // C99 6.2.5p11 (complex)
1960 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1961 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1962 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1963 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1964 bool isFloat128Type() const;
1965 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1966 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1967 bool isVoidType() const; // C99 6.2.5p19
1968 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1969 bool isAggregateType() const;
1970 bool isFundamentalType() const;
1971 bool isCompoundType() const;
1972
1973 // Type Predicates: Check to see if this type is structurally the specified
1974 // type, ignoring typedefs and qualifiers.
1975 bool isFunctionType() const;
1976 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1977 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1978 bool isPointerType() const;
1979 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1980 bool isBlockPointerType() const;
1981 bool isVoidPointerType() const;
1982 bool isReferenceType() const;
1983 bool isLValueReferenceType() const;
1984 bool isRValueReferenceType() const;
1985 bool isFunctionPointerType() const;
1986 bool isFunctionReferenceType() const;
1987 bool isMemberPointerType() const;
1988 bool isMemberFunctionPointerType() const;
1989 bool isMemberDataPointerType() const;
1990 bool isArrayType() const;
1991 bool isConstantArrayType() const;
1992 bool isIncompleteArrayType() const;
1993 bool isVariableArrayType() const;
1994 bool isDependentSizedArrayType() const;
1995 bool isRecordType() const;
1996 bool isClassType() const;
1997 bool isStructureType() const;
1998 bool isObjCBoxableRecordType() const;
1999 bool isInterfaceType() const;
2000 bool isStructureOrClassType() const;
2001 bool isUnionType() const;
2002 bool isComplexIntegerType() const; // GCC _Complex integer type.
2003 bool isVectorType() const; // GCC vector type.
2004 bool isExtVectorType() const; // Extended vector type.
2005 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2006 bool isObjCObjectPointerType() const; // pointer to ObjC object
2007 bool isObjCRetainableType() const; // ObjC object or block pointer
2008 bool isObjCLifetimeType() const; // (array of)* retainable type
2009 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2010 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2011 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2012 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2013 // for the common case.
2014 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2015 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2016 bool isObjCQualifiedIdType() const; // id<foo>
2017 bool isObjCQualifiedClassType() const; // Class<foo>
2018 bool isObjCObjectOrInterfaceType() const;
2019 bool isObjCIdType() const; // id
2020 bool isDecltypeType() const;
2021 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2022 /// qualifier?
2023 ///
2024 /// This approximates the answer to the following question: if this
2025 /// translation unit were compiled in ARC, would this type be qualified
2026 /// with __unsafe_unretained?
2027 bool isObjCInertUnsafeUnretainedType() const {
2028 return hasAttr(attr::ObjCInertUnsafeUnretained);
2029 }
2030
2031 /// Whether the type is Objective-C 'id' or a __kindof type of an
2032 /// object type, e.g., __kindof NSView * or __kindof id
2033 /// <NSCopying>.
2034 ///
2035 /// \param bound Will be set to the bound on non-id subtype types,
2036 /// which will be (possibly specialized) Objective-C class type, or
2037 /// null for 'id.
2038 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2039 const ObjCObjectType *&bound) const;
2040
2041 bool isObjCClassType() const; // Class
2042
2043 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2044 /// Class type, e.g., __kindof Class <NSCopying>.
2045 ///
2046 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2047 /// here because Objective-C's type system cannot express "a class
2048 /// object for a subclass of NSFoo".
2049 bool isObjCClassOrClassKindOfType() const;
2050
2051 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2052 bool isObjCSelType() const; // Class
2053 bool isObjCBuiltinType() const; // 'id' or 'Class'
2054 bool isObjCARCBridgableType() const;
2055 bool isCARCBridgableType() const;
2056 bool isTemplateTypeParmType() const; // C++ template type parameter
2057 bool isNullPtrType() const; // C++11 std::nullptr_t
2058 bool isNothrowT() const; // C++ std::nothrow_t
2059 bool isAlignValT() const; // C++17 std::align_val_t
2060 bool isStdByteType() const; // C++17 std::byte
2061 bool isAtomicType() const; // C11 _Atomic()
2062
2063#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2064 bool is##Id##Type() const;
2065#include "clang/Basic/OpenCLImageTypes.def"
2066
2067 bool isImageType() const; // Any OpenCL image type
2068
2069 bool isSamplerT() const; // OpenCL sampler_t
2070 bool isEventT() const; // OpenCL event_t
2071 bool isClkEventT() const; // OpenCL clk_event_t
2072 bool isQueueT() const; // OpenCL queue_t
2073 bool isReserveIDT() const; // OpenCL reserve_id_t
2074
2075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2076 bool is##Id##Type() const;
2077#include "clang/Basic/OpenCLExtensionTypes.def"
2078 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2079 bool isOCLIntelSubgroupAVCType() const;
2080 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2081
2082 bool isPipeType() const; // OpenCL pipe type
2083 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2084
2085 /// Determines if this type, which must satisfy
2086 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2087 /// than implicitly __strong.
2088 bool isObjCARCImplicitlyUnretainedType() const;
2089
2090 /// Return the implicit lifetime for this type, which must not be dependent.
2091 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2092
2093 enum ScalarTypeKind {
2094 STK_CPointer,
2095 STK_BlockPointer,
2096 STK_ObjCObjectPointer,
2097 STK_MemberPointer,
2098 STK_Bool,
2099 STK_Integral,
2100 STK_Floating,
2101 STK_IntegralComplex,
2102 STK_FloatingComplex,
2103 STK_FixedPoint
2104 };
2105
2106 /// Given that this is a scalar type, classify it.
2107 ScalarTypeKind getScalarTypeKind() const;
2108
2109 /// Whether this type is a dependent type, meaning that its definition
2110 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2111 bool isDependentType() const { return TypeBits.Dependent; }
2112
2113 /// Determine whether this type is an instantiation-dependent type,
2114 /// meaning that the type involves a template parameter (even if the
2115 /// definition does not actually depend on the type substituted for that
2116 /// template parameter).
2117 bool isInstantiationDependentType() const {
2118 return TypeBits.InstantiationDependent;
2119 }
2120
2121 /// Determine whether this type is an undeduced type, meaning that
2122 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2123 /// deduced.
2124 bool isUndeducedType() const;
2125
2126 /// Whether this type is a variably-modified type (C99 6.7.5).
2127 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2128
2129 /// Whether this type involves a variable-length array type
2130 /// with a definite size.
2131 bool hasSizedVLAType() const;
2132
2133 /// Whether this type is or contains a local or unnamed type.
2134 bool hasUnnamedOrLocalType() const;
2135
2136 bool isOverloadableType() const;
2137
2138 /// Determine wither this type is a C++ elaborated-type-specifier.
2139 bool isElaboratedTypeSpecifier() const;
2140
2141 bool canDecayToPointerType() const;
2142
2143 /// Whether this type is represented natively as a pointer. This includes
2144 /// pointers, references, block pointers, and Objective-C interface,
2145 /// qualified id, and qualified interface types, as well as nullptr_t.
2146 bool hasPointerRepresentation() const;
2147
2148 /// Whether this type can represent an objective pointer type for the
2149 /// purpose of GC'ability
2150 bool hasObjCPointerRepresentation() const;
2151
2152 /// Determine whether this type has an integer representation
2153 /// of some sort, e.g., it is an integer type or a vector.
2154 bool hasIntegerRepresentation() const;
2155
2156 /// Determine whether this type has an signed integer representation
2157 /// of some sort, e.g., it is an signed integer type or a vector.
2158 bool hasSignedIntegerRepresentation() const;
2159
2160 /// Determine whether this type has an unsigned integer representation
2161 /// of some sort, e.g., it is an unsigned integer type or a vector.
2162 bool hasUnsignedIntegerRepresentation() const;
2163
2164 /// Determine whether this type has a floating-point representation
2165 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2166 bool hasFloatingRepresentation() const;
2167
2168 // Type Checking Functions: Check to see if this type is structurally the
2169 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2170 // the best type we can.
2171 const RecordType *getAsStructureType() const;
2172 /// NOTE: getAs*ArrayType are methods on ASTContext.
2173 const RecordType *getAsUnionType() const;
2174 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2175 const ObjCObjectType *getAsObjCInterfaceType() const;
2176
2177 // The following is a convenience method that returns an ObjCObjectPointerType
2178 // for object declared using an interface.
2179 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2180 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2181 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2182 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2183
2184 /// Retrieves the CXXRecordDecl that this type refers to, either
2185 /// because the type is a RecordType or because it is the injected-class-name
2186 /// type of a class template or class template partial specialization.
2187 CXXRecordDecl *getAsCXXRecordDecl() const;
2188
2189 /// Retrieves the RecordDecl this type refers to.
2190 RecordDecl *getAsRecordDecl() const;
2191
2192 /// Retrieves the TagDecl that this type refers to, either
2193 /// because the type is a TagType or because it is the injected-class-name
2194 /// type of a class template or class template partial specialization.
2195 TagDecl *getAsTagDecl() const;
2196
2197 /// If this is a pointer or reference to a RecordType, return the
2198 /// CXXRecordDecl that the type refers to.
2199 ///
2200 /// If this is not a pointer or reference, or the type being pointed to does
2201 /// not refer to a CXXRecordDecl, returns NULL.
2202 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2203
2204 /// Get the DeducedType whose type will be deduced for a variable with
2205 /// an initializer of this type. This looks through declarators like pointer
2206 /// types, but not through decltype or typedefs.
2207 DeducedType *getContainedDeducedType() const;
2208
2209 /// Get the AutoType whose type will be deduced for a variable with
2210 /// an initializer of this type. This looks through declarators like pointer
2211 /// types, but not through decltype or typedefs.
2212 AutoType *getContainedAutoType() const {
2213 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2214 }
2215
2216 /// Determine whether this type was written with a leading 'auto'
2217 /// corresponding to a trailing return type (possibly for a nested
2218 /// function type within a pointer to function type or similar).
2219 bool hasAutoForTrailingReturnType() const;
2220
2221 /// Member-template getAs<specific type>'. Look through sugar for
2222 /// an instance of \<specific type>. This scheme will eventually
2223 /// replace the specific getAsXXXX methods above.
2224 ///
2225 /// There are some specializations of this member template listed
2226 /// immediately following this class.
2227 template <typename T> const T *getAs() const;
2228
2229 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2230 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2231 /// This is used when you need to walk over sugar nodes that represent some
2232 /// kind of type adjustment from a type that was written as a \<specific type>
2233 /// to another type that is still canonically a \<specific type>.
2234 template <typename T> const T *getAsAdjusted() const;
2235
2236 /// A variant of getAs<> for array types which silently discards
2237 /// qualifiers from the outermost type.
2238 const ArrayType *getAsArrayTypeUnsafe() const;
2239
2240 /// Member-template castAs<specific type>. Look through sugar for
2241 /// the underlying instance of \<specific type>.
2242 ///
2243 /// This method has the same relationship to getAs<T> as cast<T> has
2244 /// to dyn_cast<T>; which is to say, the underlying type *must*
2245 /// have the intended type, and this method will never return null.
2246 template <typename T> const T *castAs() const;
2247
2248 /// A variant of castAs<> for array type which silently discards
2249 /// qualifiers from the outermost type.
2250 const ArrayType *castAsArrayTypeUnsafe() const;
2251
2252 /// Determine whether this type had the specified attribute applied to it
2253 /// (looking through top-level type sugar).
2254 bool hasAttr(attr::Kind AK) const;
2255
2256 /// Get the base element type of this type, potentially discarding type
2257 /// qualifiers. This should never be used when type qualifiers
2258 /// are meaningful.
2259 const Type *getBaseElementTypeUnsafe() const;
2260
2261 /// If this is an array type, return the element type of the array,
2262 /// potentially with type qualifiers missing.
2263 /// This should never be used when type qualifiers are meaningful.
2264 const Type *getArrayElementTypeNoTypeQual() const;
2265
2266 /// If this is a pointer type, return the pointee type.
2267 /// If this is an array type, return the array element type.
2268 /// This should never be used when type qualifiers are meaningful.
2269 const Type *getPointeeOrArrayElementType() const;
2270
2271 /// If this is a pointer, ObjC object pointer, or block
2272 /// pointer, this returns the respective pointee.
2273 QualType getPointeeType() const;
2274
2275 /// Return the specified type with any "sugar" removed from the type,
2276 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2277 const Type *getUnqualifiedDesugaredType() const;
2278
2279 /// More type predicates useful for type checking/promotion
2280 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2281
2282 /// Return true if this is an integer type that is
2283 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2284 /// or an enum decl which has a signed representation.
2285 bool isSignedIntegerType() const;
2286
2287 /// Return true if this is an integer type that is
2288 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2289 /// or an enum decl which has an unsigned representation.
2290 bool isUnsignedIntegerType() const;
2291
2292 /// Determines whether this is an integer type that is signed or an
2293 /// enumeration types whose underlying type is a signed integer type.
2294 bool isSignedIntegerOrEnumerationType() const;
2295
2296 /// Determines whether this is an integer type that is unsigned or an
2297 /// enumeration types whose underlying type is a unsigned integer type.
2298 bool isUnsignedIntegerOrEnumerationType() const;
2299
2300 /// Return true if this is a fixed point type according to
2301 /// ISO/IEC JTC1 SC22 WG14 N1169.
2302 bool isFixedPointType() const;
2303
2304 /// Return true if this is a fixed point or integer type.
2305 bool isFixedPointOrIntegerType() const;
2306
2307 /// Return true if this is a saturated fixed point type according to
2308 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2309 bool isSaturatedFixedPointType() const;
2310
2311 /// Return true if this is a saturated fixed point type according to
2312 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2313 bool isUnsaturatedFixedPointType() const;
2314
2315 /// Return true if this is a fixed point type that is signed according
2316 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2317 bool isSignedFixedPointType() const;
2318
2319 /// Return true if this is a fixed point type that is unsigned according
2320 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2321 bool isUnsignedFixedPointType() const;
2322
2323 /// Return true if this is not a variable sized type,
2324 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2325 /// incomplete types.
2326 bool isConstantSizeType() const;
2327
2328 /// Returns true if this type can be represented by some
2329 /// set of type specifiers.
2330 bool isSpecifierType() const;
2331
2332 /// Determine the linkage of this type.
2333 Linkage getLinkage() const;
2334
2335 /// Determine the visibility of this type.
2336 Visibility getVisibility() const {
2337 return getLinkageAndVisibility().getVisibility();
2338 }
2339
2340 /// Return true if the visibility was explicitly set is the code.
2341 bool isVisibilityExplicit() const {
2342 return getLinkageAndVisibility().isVisibilityExplicit();
2343 }
2344
2345 /// Determine the linkage and visibility of this type.
2346 LinkageInfo getLinkageAndVisibility() const;
2347
2348 /// True if the computed linkage is valid. Used for consistency
2349 /// checking. Should always return true.
2350 bool isLinkageValid() const;
2351
2352 /// Determine the nullability of the given type.
2353 ///
2354 /// Note that nullability is only captured as sugar within the type
2355 /// system, not as part of the canonical type, so nullability will
2356 /// be lost by canonicalization and desugaring.
2357 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2358
2359 /// Determine whether the given type can have a nullability
2360 /// specifier applied to it, i.e., if it is any kind of pointer type.
2361 ///
2362 /// \param ResultIfUnknown The value to return if we don't yet know whether
2363 /// this type can have nullability because it is dependent.
2364 bool canHaveNullability(bool ResultIfUnknown = true) const;
2365
2366 /// Retrieve the set of substitutions required when accessing a member
2367 /// of the Objective-C receiver type that is declared in the given context.
2368 ///
2369 /// \c *this is the type of the object we're operating on, e.g., the
2370 /// receiver for a message send or the base of a property access, and is
2371 /// expected to be of some object or object pointer type.
2372 ///
2373 /// \param dc The declaration context for which we are building up a
2374 /// substitution mapping, which should be an Objective-C class, extension,
2375 /// category, or method within.
2376 ///
2377 /// \returns an array of type arguments that can be substituted for
2378 /// the type parameters of the given declaration context in any type described
2379 /// within that context, or an empty optional to indicate that no
2380 /// substitution is required.
2381 Optional<ArrayRef<QualType>>
2382 getObjCSubstitutions(const DeclContext *dc) const;
2383
2384 /// Determines if this is an ObjC interface type that may accept type
2385 /// parameters.
2386 bool acceptsObjCTypeParams() const;
2387
2388 const char *getTypeClassName() const;
2389
2390 QualType getCanonicalTypeInternal() const {
2391 return CanonicalType;
2392 }
2393
2394 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2395 void dump() const;
2396 void dump(llvm::raw_ostream &OS) const;
2397};
2398
2399/// This will check for a TypedefType by removing any existing sugar
2400/// until it reaches a TypedefType or a non-sugared type.
2401template <> const TypedefType *Type::getAs() const;
2402
2403/// This will check for a TemplateSpecializationType by removing any
2404/// existing sugar until it reaches a TemplateSpecializationType or a
2405/// non-sugared type.
2406template <> const TemplateSpecializationType *Type::getAs() const;
2407
2408/// This will check for an AttributedType by removing any existing sugar
2409/// until it reaches an AttributedType or a non-sugared type.
2410template <> const AttributedType *Type::getAs() const;
2411
2412// We can do canonical leaf types faster, because we don't have to
2413// worry about preserving child type decoration.
2414#define TYPE(Class, Base)
2415#define LEAF_TYPE(Class) \
2416template <> inline const Class##Type *Type::getAs() const { \
2417 return dyn_cast<Class##Type>(CanonicalType); \
2418} \
2419template <> inline const Class##Type *Type::castAs() const { \
2420 return cast<Class##Type>(CanonicalType); \
2421}
2422#include "clang/AST/TypeNodes.inc"
2423
2424/// This class is used for builtin types like 'int'. Builtin
2425/// types are always canonical and have a literal name field.
2426class BuiltinType : public Type {
2427public:
2428 enum Kind {
2429// OpenCL image types
2430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2431#include "clang/Basic/OpenCLImageTypes.def"
2432// OpenCL extension types
2433#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2434#include "clang/Basic/OpenCLExtensionTypes.def"
2435// SVE Types
2436#define SVE_TYPE(Name, Id, SingletonId) Id,
2437#include "clang/Basic/AArch64SVEACLETypes.def"
2438// All other builtin types
2439#define BUILTIN_TYPE(Id, SingletonId) Id,
2440#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2441#include "clang/AST/BuiltinTypes.def"
2442 };
2443
2444private:
2445 friend class ASTContext; // ASTContext creates these.
2446
2447 BuiltinType(Kind K)
2448 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2449 /*InstantiationDependent=*/(K == Dependent),
2450 /*VariablyModified=*/false,
2451 /*Unexpanded parameter pack=*/false) {
2452 BuiltinTypeBits.Kind = K;
2453 }
2454
2455public:
2456 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2457 StringRef getName(const PrintingPolicy &Policy) const;
2458
2459 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2460 // The StringRef is null-terminated.
2461 StringRef str = getName(Policy);
2462 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 2462, __PRETTY_FUNCTION__))
;
2463 return str.data();
2464 }
2465
2466 bool isSugared() const { return false; }
2467 QualType desugar() const { return QualType(this, 0); }
2468
2469 bool isInteger() const {
2470 return getKind() >= Bool && getKind() <= Int128;
2471 }
2472
2473 bool isSignedInteger() const {
2474 return getKind() >= Char_S && getKind() <= Int128;
2475 }
2476
2477 bool isUnsignedInteger() const {
2478 return getKind() >= Bool && getKind() <= UInt128;
2479 }
2480
2481 bool isFloatingPoint() const {
2482 return getKind() >= Half && getKind() <= Float128;
2483 }
2484
2485 /// Determines whether the given kind corresponds to a placeholder type.
2486 static bool isPlaceholderTypeKind(Kind K) {
2487 return K >= Overload;
2488 }
2489
2490 /// Determines whether this type is a placeholder type, i.e. a type
2491 /// which cannot appear in arbitrary positions in a fully-formed
2492 /// expression.
2493 bool isPlaceholderType() const {
2494 return isPlaceholderTypeKind(getKind());
2495 }
2496
2497 /// Determines whether this type is a placeholder type other than
2498 /// Overload. Most placeholder types require only syntactic
2499 /// information about their context in order to be resolved (e.g.
2500 /// whether it is a call expression), which means they can (and
2501 /// should) be resolved in an earlier "phase" of analysis.
2502 /// Overload expressions sometimes pick up further information
2503 /// from their context, like whether the context expects a
2504 /// specific function-pointer type, and so frequently need
2505 /// special treatment.
2506 bool isNonOverloadPlaceholderType() const {
2507 return getKind() > Overload;
2508 }
2509
2510 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2511};
2512
2513/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2514/// types (_Complex float etc) as well as the GCC integer complex extensions.
2515class ComplexType : public Type, public llvm::FoldingSetNode {
2516 friend class ASTContext; // ASTContext creates these.
2517
2518 QualType ElementType;
2519
2520 ComplexType(QualType Element, QualType CanonicalPtr)
2521 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2522 Element->isInstantiationDependentType(),
2523 Element->isVariablyModifiedType(),
2524 Element->containsUnexpandedParameterPack()),
2525 ElementType(Element) {}
2526
2527public:
2528 QualType getElementType() const { return ElementType; }
2529
2530 bool isSugared() const { return false; }
2531 QualType desugar() const { return QualType(this, 0); }
2532
2533 void Profile(llvm::FoldingSetNodeID &ID) {
2534 Profile(ID, getElementType());
2535 }
2536
2537 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2538 ID.AddPointer(Element.getAsOpaquePtr());
2539 }
2540
2541 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2542};
2543
2544/// Sugar for parentheses used when specifying types.
2545class ParenType : public Type, public llvm::FoldingSetNode {
2546 friend class ASTContext; // ASTContext creates these.
2547
2548 QualType Inner;
2549
2550 ParenType(QualType InnerType, QualType CanonType)
2551 : Type(Paren, CanonType, InnerType->isDependentType(),
2552 InnerType->isInstantiationDependentType(),
2553 InnerType->isVariablyModifiedType(),
2554 InnerType->containsUnexpandedParameterPack()),
2555 Inner(InnerType) {}
2556
2557public:
2558 QualType getInnerType() const { return Inner; }
2559
2560 bool isSugared() const { return true; }
2561 QualType desugar() const { return getInnerType(); }
2562
2563 void Profile(llvm::FoldingSetNodeID &ID) {
2564 Profile(ID, getInnerType());
2565 }
2566
2567 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2568 Inner.Profile(ID);
2569 }
2570
2571 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2572};
2573
2574/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2575class PointerType : public Type, public llvm::FoldingSetNode {
2576 friend class ASTContext; // ASTContext creates these.
2577
2578 QualType PointeeType;
2579
2580 PointerType(QualType Pointee, QualType CanonicalPtr)
2581 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2582 Pointee->isInstantiationDependentType(),
2583 Pointee->isVariablyModifiedType(),
2584 Pointee->containsUnexpandedParameterPack()),
2585 PointeeType(Pointee) {}
2586
2587public:
2588 QualType getPointeeType() const { return PointeeType; }
2589
2590 /// Returns true if address spaces of pointers overlap.
2591 /// OpenCL v2.0 defines conversion rules for pointers to different
2592 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2593 /// address spaces.
2594 /// CL1.1 or CL1.2:
2595 /// address spaces overlap iff they are they same.
2596 /// CL2.0 adds:
2597 /// __generic overlaps with any address space except for __constant.
2598 bool isAddressSpaceOverlapping(const PointerType &other) const {
2599 Qualifiers thisQuals = PointeeType.getQualifiers();
2600 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2601 // Address spaces overlap if at least one of them is a superset of another
2602 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2603 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2604 }
2605
2606 bool isSugared() const { return false; }
2607 QualType desugar() const { return QualType(this, 0); }
2608
2609 void Profile(llvm::FoldingSetNodeID &ID) {
2610 Profile(ID, getPointeeType());
2611 }
2612
2613 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2614 ID.AddPointer(Pointee.getAsOpaquePtr());
2615 }
2616
2617 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2618};
2619
2620/// Represents a type which was implicitly adjusted by the semantic
2621/// engine for arbitrary reasons. For example, array and function types can
2622/// decay, and function types can have their calling conventions adjusted.
2623class AdjustedType : public Type, public llvm::FoldingSetNode {
2624 QualType OriginalTy;
2625 QualType AdjustedTy;
2626
2627protected:
2628 friend class ASTContext; // ASTContext creates these.
2629
2630 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2631 QualType CanonicalPtr)
2632 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2633 OriginalTy->isInstantiationDependentType(),
2634 OriginalTy->isVariablyModifiedType(),
2635 OriginalTy->containsUnexpandedParameterPack()),
2636 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2637
2638public:
2639 QualType getOriginalType() const { return OriginalTy; }
2640 QualType getAdjustedType() const { return AdjustedTy; }
2641
2642 bool isSugared() const { return true; }
2643 QualType desugar() const { return AdjustedTy; }
2644
2645 void Profile(llvm::FoldingSetNodeID &ID) {
2646 Profile(ID, OriginalTy, AdjustedTy);
2647 }
2648
2649 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2650 ID.AddPointer(Orig.getAsOpaquePtr());
2651 ID.AddPointer(New.getAsOpaquePtr());
2652 }
2653
2654 static bool classof(const Type *T) {
2655 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2656 }
2657};
2658
2659/// Represents a pointer type decayed from an array or function type.
2660class DecayedType : public AdjustedType {
2661 friend class ASTContext; // ASTContext creates these.
2662
2663 inline
2664 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2665
2666public:
2667 QualType getDecayedType() const { return getAdjustedType(); }
2668
2669 inline QualType getPointeeType() const;
2670
2671 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2672};
2673
2674/// Pointer to a block type.
2675/// This type is to represent types syntactically represented as
2676/// "void (^)(int)", etc. Pointee is required to always be a function type.
2677class BlockPointerType : public Type, public llvm::FoldingSetNode {
2678 friend class ASTContext; // ASTContext creates these.
2679
2680 // Block is some kind of pointer type
2681 QualType PointeeType;
2682
2683 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2684 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2685 Pointee->isInstantiationDependentType(),
2686 Pointee->isVariablyModifiedType(),
2687 Pointee->containsUnexpandedParameterPack()),
2688 PointeeType(Pointee) {}
2689
2690public:
2691 // Get the pointee type. Pointee is required to always be a function type.
2692 QualType getPointeeType() const { return PointeeType; }
2693
2694 bool isSugared() const { return false; }
2695 QualType desugar() const { return QualType(this, 0); }
2696
2697 void Profile(llvm::FoldingSetNodeID &ID) {
2698 Profile(ID, getPointeeType());
2699 }
2700
2701 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2702 ID.AddPointer(Pointee.getAsOpaquePtr());
2703 }
2704
2705 static bool classof(const Type *T) {
2706 return T->getTypeClass() == BlockPointer;
2707 }
2708};
2709
2710/// Base for LValueReferenceType and RValueReferenceType
2711class ReferenceType : public Type, public llvm::FoldingSetNode {
2712 QualType PointeeType;
2713
2714protected:
2715 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2716 bool SpelledAsLValue)
2717 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2718 Referencee->isInstantiationDependentType(),
2719 Referencee->isVariablyModifiedType(),
2720 Referencee->containsUnexpandedParameterPack()),
2721 PointeeType(Referencee) {
2722 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2723 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2724 }
2725
2726public:
2727 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2728 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2729
2730 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2731
2732 QualType getPointeeType() const {
2733 // FIXME: this might strip inner qualifiers; okay?
2734 const ReferenceType *T = this;
2735 while (T->isInnerRef())
2736 T = T->PointeeType->castAs<ReferenceType>();
2737 return T->PointeeType;
2738 }
2739
2740 void Profile(llvm::FoldingSetNodeID &ID) {
2741 Profile(ID, PointeeType, isSpelledAsLValue());
2742 }
2743
2744 static void Profile(llvm::FoldingSetNodeID &ID,
2745 QualType Referencee,
2746 bool SpelledAsLValue) {
2747 ID.AddPointer(Referencee.getAsOpaquePtr());
2748 ID.AddBoolean(SpelledAsLValue);
2749 }
2750
2751 static bool classof(const Type *T) {
2752 return T->getTypeClass() == LValueReference ||
2753 T->getTypeClass() == RValueReference;
2754 }
2755};
2756
2757/// An lvalue reference type, per C++11 [dcl.ref].
2758class LValueReferenceType : public ReferenceType {
2759 friend class ASTContext; // ASTContext creates these
2760
2761 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2762 bool SpelledAsLValue)
2763 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2764 SpelledAsLValue) {}
2765
2766public:
2767 bool isSugared() const { return false; }
2768 QualType desugar() const { return QualType(this, 0); }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == LValueReference;
2772 }
2773};
2774
2775/// An rvalue reference type, per C++11 [dcl.ref].
2776class RValueReferenceType : public ReferenceType {
2777 friend class ASTContext; // ASTContext creates these
2778
2779 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2780 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2781
2782public:
2783 bool isSugared() const { return false; }
2784 QualType desugar() const { return QualType(this, 0); }
2785
2786 static bool classof(const Type *T) {
2787 return T->getTypeClass() == RValueReference;
2788 }
2789};
2790
2791/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2792///
2793/// This includes both pointers to data members and pointer to member functions.
2794class MemberPointerType : public Type, public llvm::FoldingSetNode {
2795 friend class ASTContext; // ASTContext creates these.
2796
2797 QualType PointeeType;
2798
2799 /// The class of which the pointee is a member. Must ultimately be a
2800 /// RecordType, but could be a typedef or a template parameter too.
2801 const Type *Class;
2802
2803 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2804 : Type(MemberPointer, CanonicalPtr,
2805 Cls->isDependentType() || Pointee->isDependentType(),
2806 (Cls->isInstantiationDependentType() ||
2807 Pointee->isInstantiationDependentType()),
2808 Pointee->isVariablyModifiedType(),
2809 (Cls->containsUnexpandedParameterPack() ||
2810 Pointee->containsUnexpandedParameterPack())),
2811 PointeeType(Pointee), Class(Cls) {}
2812
2813public:
2814 QualType getPointeeType() const { return PointeeType; }
2815
2816 /// Returns true if the member type (i.e. the pointee type) is a
2817 /// function type rather than a data-member type.
2818 bool isMemberFunctionPointer() const {
2819 return PointeeType->isFunctionProtoType();
2820 }
2821
2822 /// Returns true if the member type (i.e. the pointee type) is a
2823 /// data type rather than a function type.
2824 bool isMemberDataPointer() const {
2825 return !PointeeType->isFunctionProtoType();
2826 }
2827
2828 const Type *getClass() const { return Class; }
2829 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2830
2831 bool isSugared() const { return false; }
2832 QualType desugar() const { return QualType(this, 0); }
2833
2834 void Profile(llvm::FoldingSetNodeID &ID) {
2835 Profile(ID, getPointeeType(), getClass());
2836 }
2837
2838 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2839 const Type *Class) {
2840 ID.AddPointer(Pointee.getAsOpaquePtr());
2841 ID.AddPointer(Class);
2842 }
2843
2844 static bool classof(const Type *T) {
2845 return T->getTypeClass() == MemberPointer;
2846 }
2847};
2848
2849/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2850class ArrayType : public Type, public llvm::FoldingSetNode {
2851public:
2852 /// Capture whether this is a normal array (e.g. int X[4])
2853 /// an array with a static size (e.g. int X[static 4]), or an array
2854 /// with a star size (e.g. int X[*]).
2855 /// 'static' is only allowed on function parameters.
2856 enum ArraySizeModifier {
2857 Normal, Static, Star
2858 };
2859
2860private:
2861 /// The element type of the array.
2862 QualType ElementType;
2863
2864protected:
2865 friend class ASTContext; // ASTContext creates these.
2866
2867 // C++ [temp.dep.type]p1:
2868 // A type is dependent if it is...
2869 // - an array type constructed from any dependent type or whose
2870 // size is specified by a constant expression that is
2871 // value-dependent,
2872 ArrayType(TypeClass tc, QualType et, QualType can,
2873 ArraySizeModifier sm, unsigned tq,
2874 bool ContainsUnexpandedParameterPack)
2875 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2876 et->isInstantiationDependentType() || tc == DependentSizedArray,
2877 (tc == VariableArray || et->isVariablyModifiedType()),
2878 ContainsUnexpandedParameterPack),
2879 ElementType(et) {
2880 ArrayTypeBits.IndexTypeQuals = tq;
2881 ArrayTypeBits.SizeModifier = sm;
2882 }
2883
2884public:
2885 QualType getElementType() const { return ElementType; }
2886
2887 ArraySizeModifier getSizeModifier() const {
2888 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2889 }
2890
2891 Qualifiers getIndexTypeQualifiers() const {
2892 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2893 }
2894
2895 unsigned getIndexTypeCVRQualifiers() const {
2896 return ArrayTypeBits.IndexTypeQuals;
2897 }
2898
2899 static bool classof(const Type *T) {
2900 return T->getTypeClass() == ConstantArray ||
2901 T->getTypeClass() == VariableArray ||
2902 T->getTypeClass() == IncompleteArray ||
2903 T->getTypeClass() == DependentSizedArray;
2904 }
2905};
2906
2907/// Represents the canonical version of C arrays with a specified constant size.
2908/// For example, the canonical type for 'int A[4 + 4*100]' is a
2909/// ConstantArrayType where the element type is 'int' and the size is 404.
2910class ConstantArrayType : public ArrayType {
2911 llvm::APInt Size; // Allows us to unique the type.
2912
2913 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2914 ArraySizeModifier sm, unsigned tq)
2915 : ArrayType(ConstantArray, et, can, sm, tq,
2916 et->containsUnexpandedParameterPack()),
2917 Size(size) {}
2918
2919protected:
2920 friend class ASTContext; // ASTContext creates these.
2921
2922 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2923 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2924 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2925 Size(size) {}
2926
2927public:
2928 const llvm::APInt &getSize() const { return Size; }
2929 bool isSugared() const { return false; }
2930 QualType desugar() const { return QualType(this, 0); }
2931
2932 /// Determine the number of bits required to address a member of
2933 // an array with the given element type and number of elements.
2934 static unsigned getNumAddressingBits(const ASTContext &Context,
2935 QualType ElementType,
2936 const llvm::APInt &NumElements);
2937
2938 /// Determine the maximum number of active bits that an array's size
2939 /// can require, which limits the maximum size of the array.
2940 static unsigned getMaxSizeBits(const ASTContext &Context);
2941
2942 void Profile(llvm::FoldingSetNodeID &ID) {
2943 Profile(ID, getElementType(), getSize(),
2944 getSizeModifier(), getIndexTypeCVRQualifiers());
2945 }
2946
2947 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2948 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2949 unsigned TypeQuals) {
2950 ID.AddPointer(ET.getAsOpaquePtr());
2951 ID.AddInteger(ArraySize.getZExtValue());
2952 ID.AddInteger(SizeMod);
2953 ID.AddInteger(TypeQuals);
2954 }
2955
2956 static bool classof(const Type *T) {
2957 return T->getTypeClass() == ConstantArray;
2958 }
2959};
2960
2961/// Represents a C array with an unspecified size. For example 'int A[]' has
2962/// an IncompleteArrayType where the element type is 'int' and the size is
2963/// unspecified.
2964class IncompleteArrayType : public ArrayType {
2965 friend class ASTContext; // ASTContext creates these.
2966
2967 IncompleteArrayType(QualType et, QualType can,
2968 ArraySizeModifier sm, unsigned tq)
2969 : ArrayType(IncompleteArray, et, can, sm, tq,
2970 et->containsUnexpandedParameterPack()) {}
2971
2972public:
2973 friend class StmtIteratorBase;
2974
2975 bool isSugared() const { return false; }
2976 QualType desugar() const { return QualType(this, 0); }
2977
2978 static bool classof(const Type *T) {
2979 return T->getTypeClass() == IncompleteArray;
2980 }
2981
2982 void Profile(llvm::FoldingSetNodeID &ID) {
2983 Profile(ID, getElementType(), getSizeModifier(),
2984 getIndexTypeCVRQualifiers());
2985 }
2986
2987 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2988 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2989 ID.AddPointer(ET.getAsOpaquePtr());
2990 ID.AddInteger(SizeMod);
2991 ID.AddInteger(TypeQuals);
2992 }
2993};
2994
2995/// Represents a C array with a specified size that is not an
2996/// integer-constant-expression. For example, 'int s[x+foo()]'.
2997/// Since the size expression is an arbitrary expression, we store it as such.
2998///
2999/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3000/// should not be: two lexically equivalent variable array types could mean
3001/// different things, for example, these variables do not have the same type
3002/// dynamically:
3003///
3004/// void foo(int x) {
3005/// int Y[x];
3006/// ++x;
3007/// int Z[x];
3008/// }
3009class VariableArrayType : public ArrayType {
3010 friend class ASTContext; // ASTContext creates these.
3011
3012 /// An assignment-expression. VLA's are only permitted within
3013 /// a function block.
3014 Stmt *SizeExpr;
3015
3016 /// The range spanned by the left and right array brackets.
3017 SourceRange Brackets;
3018
3019 VariableArrayType(QualType et, QualType can, Expr *e,
3020 ArraySizeModifier sm, unsigned tq,
3021 SourceRange brackets)
3022 : ArrayType(VariableArray, et, can, sm, tq,
3023 et->containsUnexpandedParameterPack()),
3024 SizeExpr((Stmt*) e), Brackets(brackets) {}
3025
3026public:
3027 friend class StmtIteratorBase;
3028
3029 Expr *getSizeExpr() const {
3030 // We use C-style casts instead of cast<> here because we do not wish
3031 // to have a dependency of Type.h on Stmt.h/Expr.h.
3032 return (Expr*) SizeExpr;
3033 }
3034
3035 SourceRange getBracketsRange() const { return Brackets; }
3036 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3037 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3038
3039 bool isSugared() const { return false; }
3040 QualType desugar() const { return QualType(this, 0); }
3041
3042 static bool classof(const Type *T) {
3043 return T->getTypeClass() == VariableArray;
3044 }
3045
3046 void Profile(llvm::FoldingSetNodeID &ID) {
3047 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3047)
;
3048 }
3049};
3050
3051/// Represents an array type in C++ whose size is a value-dependent expression.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int Size>
3056/// class array {
3057/// T data[Size];
3058/// };
3059/// \endcode
3060///
3061/// For these types, we won't actually know what the array bound is
3062/// until template instantiation occurs, at which point this will
3063/// become either a ConstantArrayType or a VariableArrayType.
3064class DependentSizedArrayType : public ArrayType {
3065 friend class ASTContext; // ASTContext creates these.
3066
3067 const ASTContext &Context;
3068
3069 /// An assignment expression that will instantiate to the
3070 /// size of the array.
3071 ///
3072 /// The expression itself might be null, in which case the array
3073 /// type will have its size deduced from an initializer.
3074 Stmt *SizeExpr;
3075
3076 /// The range spanned by the left and right array brackets.
3077 SourceRange Brackets;
3078
3079 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3080 Expr *e, ArraySizeModifier sm, unsigned tq,
3081 SourceRange brackets);
3082
3083public:
3084 friend class StmtIteratorBase;
3085
3086 Expr *getSizeExpr() const {
3087 // We use C-style casts instead of cast<> here because we do not wish
3088 // to have a dependency of Type.h on Stmt.h/Expr.h.
3089 return (Expr*) SizeExpr;
3090 }
3091
3092 SourceRange getBracketsRange() const { return Brackets; }
3093 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3094 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3095
3096 bool isSugared() const { return false; }
3097 QualType desugar() const { return QualType(this, 0); }
3098
3099 static bool classof(const Type *T) {
3100 return T->getTypeClass() == DependentSizedArray;
3101 }
3102
3103 void Profile(llvm::FoldingSetNodeID &ID) {
3104 Profile(ID, Context, getElementType(),
3105 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3106 }
3107
3108 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3109 QualType ET, ArraySizeModifier SizeMod,
3110 unsigned TypeQuals, Expr *E);
3111};
3112
3113/// Represents an extended address space qualifier where the input address space
3114/// value is dependent. Non-dependent address spaces are not represented with a
3115/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3116///
3117/// For example:
3118/// \code
3119/// template<typename T, int AddrSpace>
3120/// class AddressSpace {
3121/// typedef T __attribute__((address_space(AddrSpace))) type;
3122/// }
3123/// \endcode
3124class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3125 friend class ASTContext;
3126
3127 const ASTContext &Context;
3128 Expr *AddrSpaceExpr;
3129 QualType PointeeType;
3130 SourceLocation loc;
3131
3132 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3133 QualType can, Expr *AddrSpaceExpr,
3134 SourceLocation loc);
3135
3136public:
3137 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3138 QualType getPointeeType() const { return PointeeType; }
3139 SourceLocation getAttributeLoc() const { return loc; }
3140
3141 bool isSugared() const { return false; }
3142 QualType desugar() const { return QualType(this, 0); }
3143
3144 static bool classof(const Type *T) {
3145 return T->getTypeClass() == DependentAddressSpace;
3146 }
3147
3148 void Profile(llvm::FoldingSetNodeID &ID) {
3149 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3150 }
3151
3152 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3153 QualType PointeeType, Expr *AddrSpaceExpr);
3154};
3155
3156/// Represents an extended vector type where either the type or size is
3157/// dependent.
3158///
3159/// For example:
3160/// \code
3161/// template<typename T, int Size>
3162/// class vector {
3163/// typedef T __attribute__((ext_vector_type(Size))) type;
3164/// }
3165/// \endcode
3166class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3167 friend class ASTContext;
3168
3169 const ASTContext &Context;
3170 Expr *SizeExpr;
3171
3172 /// The element type of the array.
3173 QualType ElementType;
3174
3175 SourceLocation loc;
3176
3177 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3178 QualType can, Expr *SizeExpr, SourceLocation loc);
3179
3180public:
3181 Expr *getSizeExpr() const { return SizeExpr; }
3182 QualType getElementType() const { return ElementType; }
3183 SourceLocation getAttributeLoc() const { return loc; }
3184
3185 bool isSugared() const { return false; }
3186 QualType desugar() const { return QualType(this, 0); }
3187
3188 static bool classof(const Type *T) {
3189 return T->getTypeClass() == DependentSizedExtVector;
3190 }
3191
3192 void Profile(llvm::FoldingSetNodeID &ID) {
3193 Profile(ID, Context, getElementType(), getSizeExpr());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 QualType ElementType, Expr *SizeExpr);
3198};
3199
3200
3201/// Represents a GCC generic vector type. This type is created using
3202/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3203/// bytes; or from an Altivec __vector or vector declaration.
3204/// Since the constructor takes the number of vector elements, the
3205/// client is responsible for converting the size into the number of elements.
3206class VectorType : public Type, public llvm::FoldingSetNode {
3207public:
3208 enum VectorKind {
3209 /// not a target-specific vector type
3210 GenericVector,
3211
3212 /// is AltiVec vector
3213 AltiVecVector,
3214
3215 /// is AltiVec 'vector Pixel'
3216 AltiVecPixel,
3217
3218 /// is AltiVec 'vector bool ...'
3219 AltiVecBool,
3220
3221 /// is ARM Neon vector
3222 NeonVector,
3223
3224 /// is ARM Neon polynomial vector
3225 NeonPolyVector
3226 };
3227
3228protected:
3229 friend class ASTContext; // ASTContext creates these.
3230
3231 /// The element type of the vector.
3232 QualType ElementType;
3233
3234 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3235 VectorKind vecKind);
3236
3237 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3238 QualType canonType, VectorKind vecKind);
3239
3240public:
3241 QualType getElementType() const { return ElementType; }
3242 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3243
3244 static bool isVectorSizeTooLarge(unsigned NumElements) {
3245 return NumElements > VectorTypeBitfields::MaxNumElements;
3246 }
3247
3248 bool isSugared() const { return false; }
3249 QualType desugar() const { return QualType(this, 0); }
3250
3251 VectorKind getVectorKind() const {
3252 return VectorKind(VectorTypeBits.VecKind);
3253 }
3254
3255 void Profile(llvm::FoldingSetNodeID &ID) {
3256 Profile(ID, getElementType(), getNumElements(),
3257 getTypeClass(), getVectorKind());
3258 }
3259
3260 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3261 unsigned NumElements, TypeClass TypeClass,
3262 VectorKind VecKind) {
3263 ID.AddPointer(ElementType.getAsOpaquePtr());
3264 ID.AddInteger(NumElements);
3265 ID.AddInteger(TypeClass);
3266 ID.AddInteger(VecKind);
3267 }
3268
3269 static bool classof(const Type *T) {
3270 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3271 }
3272};
3273
3274/// Represents a vector type where either the type or size is dependent.
3275////
3276/// For example:
3277/// \code
3278/// template<typename T, int Size>
3279/// class vector {
3280/// typedef T __attribute__((vector_size(Size))) type;
3281/// }
3282/// \endcode
3283class DependentVectorType : public Type, public llvm::FoldingSetNode {
3284 friend class ASTContext;
3285
3286 const ASTContext &Context;
3287 QualType ElementType;
3288 Expr *SizeExpr;
3289 SourceLocation Loc;
3290
3291 DependentVectorType(const ASTContext &Context, QualType ElementType,
3292 QualType CanonType, Expr *SizeExpr,
3293 SourceLocation Loc, VectorType::VectorKind vecKind);
3294
3295public:
3296 Expr *getSizeExpr() const { return SizeExpr; }
3297 QualType getElementType() const { return ElementType; }
3298 SourceLocation getAttributeLoc() const { return Loc; }
3299 VectorType::VectorKind getVectorKind() const {
3300 return VectorType::VectorKind(VectorTypeBits.VecKind);
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 static bool classof(const Type *T) {
3307 return T->getTypeClass() == DependentVector;
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3312 }
3313
3314 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3315 QualType ElementType, const Expr *SizeExpr,
3316 VectorType::VectorKind VecKind);
3317};
3318
3319/// ExtVectorType - Extended vector type. This type is created using
3320/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3321/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3322/// class enables syntactic extensions, like Vector Components for accessing
3323/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3324/// Shading Language).
3325class ExtVectorType : public VectorType {
3326 friend class ASTContext; // ASTContext creates these.
3327
3328 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3329 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3330
3331public:
3332 static int getPointAccessorIdx(char c) {
3333 switch (c) {
3334 default: return -1;
3335 case 'x': case 'r': return 0;
3336 case 'y': case 'g': return 1;
3337 case 'z': case 'b': return 2;
3338 case 'w': case 'a': return 3;
3339 }
3340 }
3341
3342 static int getNumericAccessorIdx(char c) {
3343 switch (c) {
3344 default: return -1;
3345 case '0': return 0;
3346 case '1': return 1;
3347 case '2': return 2;
3348 case '3': return 3;
3349 case '4': return 4;
3350 case '5': return 5;
3351 case '6': return 6;
3352 case '7': return 7;
3353 case '8': return 8;
3354 case '9': return 9;
3355 case 'A':
3356 case 'a': return 10;
3357 case 'B':
3358 case 'b': return 11;
3359 case 'C':
3360 case 'c': return 12;
3361 case 'D':
3362 case 'd': return 13;
3363 case 'E':
3364 case 'e': return 14;
3365 case 'F':
3366 case 'f': return 15;
3367 }
3368 }
3369
3370 static int getAccessorIdx(char c, bool isNumericAccessor) {
3371 if (isNumericAccessor)
3372 return getNumericAccessorIdx(c);
3373 else
3374 return getPointAccessorIdx(c);
3375 }
3376
3377 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3378 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3379 return unsigned(idx-1) < getNumElements();
3380 return false;
3381 }
3382
3383 bool isSugared() const { return false; }
3384 QualType desugar() const { return QualType(this, 0); }
3385
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == ExtVector;
3388 }
3389};
3390
3391/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3392/// class of FunctionNoProtoType and FunctionProtoType.
3393class FunctionType : public Type {
3394 // The type returned by the function.
3395 QualType ResultType;
3396
3397public:
3398 /// Interesting information about a specific parameter that can't simply
3399 /// be reflected in parameter's type. This is only used by FunctionProtoType
3400 /// but is in FunctionType to make this class available during the
3401 /// specification of the bases of FunctionProtoType.
3402 ///
3403 /// It makes sense to model language features this way when there's some
3404 /// sort of parameter-specific override (such as an attribute) that
3405 /// affects how the function is called. For example, the ARC ns_consumed
3406 /// attribute changes whether a parameter is passed at +0 (the default)
3407 /// or +1 (ns_consumed). This must be reflected in the function type,
3408 /// but isn't really a change to the parameter type.
3409 ///
3410 /// One serious disadvantage of modelling language features this way is
3411 /// that they generally do not work with language features that attempt
3412 /// to destructure types. For example, template argument deduction will
3413 /// not be able to match a parameter declared as
3414 /// T (*)(U)
3415 /// against an argument of type
3416 /// void (*)(__attribute__((ns_consumed)) id)
3417 /// because the substitution of T=void, U=id into the former will
3418 /// not produce the latter.
3419 class ExtParameterInfo {
3420 enum {
3421 ABIMask = 0x0F,
3422 IsConsumed = 0x10,
3423 HasPassObjSize = 0x20,
3424 IsNoEscape = 0x40,
3425 };
3426 unsigned char Data = 0;
3427
3428 public:
3429 ExtParameterInfo() = default;
3430
3431 /// Return the ABI treatment of this parameter.
3432 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3433 ExtParameterInfo withABI(ParameterABI kind) const {
3434 ExtParameterInfo copy = *this;
3435 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3436 return copy;
3437 }
3438
3439 /// Is this parameter considered "consumed" by Objective-C ARC?
3440 /// Consumed parameters must have retainable object type.
3441 bool isConsumed() const { return (Data & IsConsumed); }
3442 ExtParameterInfo withIsConsumed(bool consumed) const {
3443 ExtParameterInfo copy = *this;
3444 if (consumed)
3445 copy.Data |= IsConsumed;
3446 else
3447 copy.Data &= ~IsConsumed;
3448 return copy;
3449 }
3450
3451 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3452 ExtParameterInfo withHasPassObjectSize() const {
3453 ExtParameterInfo Copy = *this;
3454 Copy.Data |= HasPassObjSize;
3455 return Copy;
3456 }
3457
3458 bool isNoEscape() const { return Data & IsNoEscape; }
3459 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3460 ExtParameterInfo Copy = *this;
3461 if (NoEscape)
3462 Copy.Data |= IsNoEscape;
3463 else
3464 Copy.Data &= ~IsNoEscape;
3465 return Copy;
3466 }
3467
3468 unsigned char getOpaqueValue() const { return Data; }
3469 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3470 ExtParameterInfo result;
3471 result.Data = data;
3472 return result;
3473 }
3474
3475 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3476 return lhs.Data == rhs.Data;
3477 }
3478
3479 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3480 return lhs.Data != rhs.Data;
3481 }
3482 };
3483
3484 /// A class which abstracts out some details necessary for
3485 /// making a call.
3486 ///
3487 /// It is not actually used directly for storing this information in
3488 /// a FunctionType, although FunctionType does currently use the
3489 /// same bit-pattern.
3490 ///
3491 // If you add a field (say Foo), other than the obvious places (both,
3492 // constructors, compile failures), what you need to update is
3493 // * Operator==
3494 // * getFoo
3495 // * withFoo
3496 // * functionType. Add Foo, getFoo.
3497 // * ASTContext::getFooType
3498 // * ASTContext::mergeFunctionTypes
3499 // * FunctionNoProtoType::Profile
3500 // * FunctionProtoType::Profile
3501 // * TypePrinter::PrintFunctionProto
3502 // * AST read and write
3503 // * Codegen
3504 class ExtInfo {
3505 friend class FunctionType;
3506
3507 // Feel free to rearrange or add bits, but if you go over 12,
3508 // you'll need to adjust both the Bits field below and
3509 // Type::FunctionTypeBitfields.
3510
3511 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3512 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3513 //
3514 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3515 enum { CallConvMask = 0x1F };
3516 enum { NoReturnMask = 0x20 };
3517 enum { ProducesResultMask = 0x40 };
3518 enum { NoCallerSavedRegsMask = 0x80 };
3519 enum { NoCfCheckMask = 0x800 };
3520 enum {
3521 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3522 NoCallerSavedRegsMask | NoCfCheckMask),
3523 RegParmOffset = 8
3524 }; // Assumed to be the last field
3525 uint16_t Bits = CC_C;
3526
3527 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3528
3529 public:
3530 // Constructor with no defaults. Use this when you know that you
3531 // have all the elements (when reading an AST file for example).
3532 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3533 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3534 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3534, __PRETTY_FUNCTION__))
;
3535 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3536 (producesResult ? ProducesResultMask : 0) |
3537 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3538 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3539 (NoCfCheck ? NoCfCheckMask : 0);
3540 }
3541
3542 // Constructor with all defaults. Use when for example creating a
3543 // function known to use defaults.
3544 ExtInfo() = default;
3545
3546 // Constructor with just the calling convention, which is an important part
3547 // of the canonical type.
3548 ExtInfo(CallingConv CC) : Bits(CC) {}
3549
3550 bool getNoReturn() const { return Bits & NoReturnMask; }
3551 bool getProducesResult() const { return Bits & ProducesResultMask; }
3552 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3553 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3554 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3555
3556 unsigned getRegParm() const {
3557 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3558 if (RegParm > 0)
3559 --RegParm;
3560 return RegParm;
3561 }
3562
3563 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3564
3565 bool operator==(ExtInfo Other) const {
3566 return Bits == Other.Bits;
3567 }
3568 bool operator!=(ExtInfo Other) const {
3569 return Bits != Other.Bits;
3570 }
3571
3572 // Note that we don't have setters. That is by design, use
3573 // the following with methods instead of mutating these objects.
3574
3575 ExtInfo withNoReturn(bool noReturn) const {
3576 if (noReturn)
3577 return ExtInfo(Bits | NoReturnMask);
3578 else
3579 return ExtInfo(Bits & ~NoReturnMask);
3580 }
3581
3582 ExtInfo withProducesResult(bool producesResult) const {
3583 if (producesResult)
3584 return ExtInfo(Bits | ProducesResultMask);
3585 else
3586 return ExtInfo(Bits & ~ProducesResultMask);
3587 }
3588
3589 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3590 if (noCallerSavedRegs)
3591 return ExtInfo(Bits | NoCallerSavedRegsMask);
3592 else
3593 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3594 }
3595
3596 ExtInfo withNoCfCheck(bool noCfCheck) const {
3597 if (noCfCheck)
3598 return ExtInfo(Bits | NoCfCheckMask);
3599 else
3600 return ExtInfo(Bits & ~NoCfCheckMask);
3601 }
3602
3603 ExtInfo withRegParm(unsigned RegParm) const {
3604 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3604, __PRETTY_FUNCTION__))
;
3605 return ExtInfo((Bits & ~RegParmMask) |
3606 ((RegParm + 1) << RegParmOffset));
3607 }
3608
3609 ExtInfo withCallingConv(CallingConv cc) const {
3610 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3611 }
3612
3613 void Profile(llvm::FoldingSetNodeID &ID) const {
3614 ID.AddInteger(Bits);
3615 }
3616 };
3617
3618 /// A simple holder for a QualType representing a type in an
3619 /// exception specification. Unfortunately needed by FunctionProtoType
3620 /// because TrailingObjects cannot handle repeated types.
3621 struct ExceptionType { QualType Type; };
3622
3623 /// A simple holder for various uncommon bits which do not fit in
3624 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3625 /// alignment of subsequent objects in TrailingObjects. You must update
3626 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3627 struct alignas(void *) FunctionTypeExtraBitfields {
3628 /// The number of types in the exception specification.
3629 /// A whole unsigned is not needed here and according to
3630 /// [implimits] 8 bits would be enough here.
3631 unsigned NumExceptionType;
3632 };
3633
3634protected:
3635 FunctionType(TypeClass tc, QualType res,
3636 QualType Canonical, bool Dependent,
3637 bool InstantiationDependent,
3638 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3639 ExtInfo Info)
3640 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3641 ContainsUnexpandedParameterPack),
3642 ResultType(res) {
3643 FunctionTypeBits.ExtInfo = Info.Bits;
3644 }
3645
3646 Qualifiers getFastTypeQuals() const {
3647 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3648 }
3649
3650public:
3651 QualType getReturnType() const { return ResultType; }
3652
3653 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3654 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3655
3656 /// Determine whether this function type includes the GNU noreturn
3657 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3658 /// type.
3659 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3660
3661 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3662 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3663
3664 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3665 "Const, volatile and restrict are assumed to be a subset of "
3666 "the fast qualifiers.");
3667
3668 bool isConst() const { return getFastTypeQuals().hasConst(); }
3669 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3670 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3671
3672 /// Determine the type of an expression that calls a function of
3673 /// this type.
3674 QualType getCallResultType(const ASTContext &Context) const {
3675 return getReturnType().getNonLValueExprType(Context);
3676 }
3677
3678 static StringRef getNameForCallConv(CallingConv CC);
3679
3680 static bool classof(const Type *T) {
3681 return T->getTypeClass() == FunctionNoProto ||
3682 T->getTypeClass() == FunctionProto;
3683 }
3684};
3685
3686/// Represents a K&R-style 'int foo()' function, which has
3687/// no information available about its arguments.
3688class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3689 friend class ASTContext; // ASTContext creates these.
3690
3691 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3692 : FunctionType(FunctionNoProto, Result, Canonical,
3693 /*Dependent=*/false, /*InstantiationDependent=*/false,
3694 Result->isVariablyModifiedType(),
3695 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3696
3697public:
3698 // No additional state past what FunctionType provides.
3699
3700 bool isSugared() const { return false; }
3701 QualType desugar() const { return QualType(this, 0); }
3702
3703 void Profile(llvm::FoldingSetNodeID &ID) {
3704 Profile(ID, getReturnType(), getExtInfo());
3705 }
3706
3707 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3708 ExtInfo Info) {
3709 Info.Profile(ID);
3710 ID.AddPointer(ResultType.getAsOpaquePtr());
3711 }
3712
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() == FunctionNoProto;
3715 }
3716};
3717
3718/// Represents a prototype with parameter type info, e.g.
3719/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3720/// parameters, not as having a single void parameter. Such a type can have
3721/// an exception specification, but this specification is not part of the
3722/// canonical type. FunctionProtoType has several trailing objects, some of
3723/// which optional. For more information about the trailing objects see
3724/// the first comment inside FunctionProtoType.
3725class FunctionProtoType final
3726 : public FunctionType,
3727 public llvm::FoldingSetNode,
3728 private llvm::TrailingObjects<
3729 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3730 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3731 FunctionType::ExtParameterInfo, Qualifiers> {
3732 friend class ASTContext; // ASTContext creates these.
3733 friend TrailingObjects;
3734
3735 // FunctionProtoType is followed by several trailing objects, some of
3736 // which optional. They are in order:
3737 //
3738 // * An array of getNumParams() QualType holding the parameter types.
3739 // Always present. Note that for the vast majority of FunctionProtoType,
3740 // these will be the only trailing objects.
3741 //
3742 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3743 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3744 // a single FunctionTypeExtraBitfields. Present if and only if
3745 // hasExtraBitfields() is true.
3746 //
3747 // * Optionally exactly one of:
3748 // * an array of getNumExceptions() ExceptionType,
3749 // * a single Expr *,
3750 // * a pair of FunctionDecl *,
3751 // * a single FunctionDecl *
3752 // used to store information about the various types of exception
3753 // specification. See getExceptionSpecSize for the details.
3754 //
3755 // * Optionally an array of getNumParams() ExtParameterInfo holding
3756 // an ExtParameterInfo for each of the parameters. Present if and
3757 // only if hasExtParameterInfos() is true.
3758 //
3759 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3760 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3761 // if hasExtQualifiers() is true.
3762 //
3763 // The optional FunctionTypeExtraBitfields has to be before the data
3764 // related to the exception specification since it contains the number
3765 // of exception types.
3766 //
3767 // We put the ExtParameterInfos last. If all were equal, it would make
3768 // more sense to put these before the exception specification, because
3769 // it's much easier to skip past them compared to the elaborate switch
3770 // required to skip the exception specification. However, all is not
3771 // equal; ExtParameterInfos are used to model very uncommon features,
3772 // and it's better not to burden the more common paths.
3773
3774public:
3775 /// Holds information about the various types of exception specification.
3776 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3777 /// used to group together the various bits of information about the
3778 /// exception specification.
3779 struct ExceptionSpecInfo {
3780 /// The kind of exception specification this is.
3781 ExceptionSpecificationType Type = EST_None;
3782
3783 /// Explicitly-specified list of exception types.
3784 ArrayRef<QualType> Exceptions;
3785
3786 /// Noexcept expression, if this is a computed noexcept specification.
3787 Expr *NoexceptExpr = nullptr;
3788
3789 /// The function whose exception specification this is, for
3790 /// EST_Unevaluated and EST_Uninstantiated.
3791 FunctionDecl *SourceDecl = nullptr;
3792
3793 /// The function template whose exception specification this is instantiated
3794 /// from, for EST_Uninstantiated.
3795 FunctionDecl *SourceTemplate = nullptr;
3796
3797 ExceptionSpecInfo() = default;
3798
3799 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3800 };
3801
3802 /// Extra information about a function prototype. ExtProtoInfo is not
3803 /// stored as such in FunctionProtoType but is used to group together
3804 /// the various bits of extra information about a function prototype.
3805 struct ExtProtoInfo {
3806 FunctionType::ExtInfo ExtInfo;
3807 bool Variadic : 1;
3808 bool HasTrailingReturn : 1;
3809 Qualifiers TypeQuals;
3810 RefQualifierKind RefQualifier = RQ_None;
3811 ExceptionSpecInfo ExceptionSpec;
3812 const ExtParameterInfo *ExtParameterInfos = nullptr;
3813
3814 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3815
3816 ExtProtoInfo(CallingConv CC)
3817 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3818
3819 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3820 ExtProtoInfo Result(*this);
3821 Result.ExceptionSpec = ESI;
3822 return Result;
3823 }
3824 };
3825
3826private:
3827 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3828 return getNumParams();
3829 }
3830
3831 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3832 return hasExtraBitfields();
3833 }
3834
3835 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3836 return getExceptionSpecSize().NumExceptionType;
3837 }
3838
3839 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3840 return getExceptionSpecSize().NumExprPtr;
3841 }
3842
3843 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3844 return getExceptionSpecSize().NumFunctionDeclPtr;
3845 }
3846
3847 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3848 return hasExtParameterInfos() ? getNumParams() : 0;
3849 }
3850
3851 /// Determine whether there are any argument types that
3852 /// contain an unexpanded parameter pack.
3853 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3854 unsigned numArgs) {
3855 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3856 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3857 return true;
3858
3859 return false;
3860 }
3861
3862 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3863 QualType canonical, const ExtProtoInfo &epi);
3864
3865 /// This struct is returned by getExceptionSpecSize and is used to
3866 /// translate an ExceptionSpecificationType to the number and kind
3867 /// of trailing objects related to the exception specification.
3868 struct ExceptionSpecSizeHolder {
3869 unsigned NumExceptionType;
3870 unsigned NumExprPtr;
3871 unsigned NumFunctionDeclPtr;
3872 };
3873
3874 /// Return the number and kind of trailing objects
3875 /// related to the exception specification.
3876 static ExceptionSpecSizeHolder
3877 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3878 switch (EST) {
3879 case EST_None:
3880 case EST_DynamicNone:
3881 case EST_MSAny:
3882 case EST_BasicNoexcept:
3883 case EST_Unparsed:
3884 case EST_NoThrow:
3885 return {0, 0, 0};
3886
3887 case EST_Dynamic:
3888 return {NumExceptions, 0, 0};
3889
3890 case EST_DependentNoexcept:
3891 case EST_NoexceptFalse:
3892 case EST_NoexceptTrue:
3893 return {0, 1, 0};
3894
3895 case EST_Uninstantiated:
3896 return {0, 0, 2};
3897
3898 case EST_Unevaluated:
3899 return {0, 0, 1};
3900 }
3901 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3901)
;
3902 }
3903
3904 /// Return the number and kind of trailing objects
3905 /// related to the exception specification.
3906 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3907 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3908 }
3909
3910 /// Whether the trailing FunctionTypeExtraBitfields is present.
3911 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3912 // If the exception spec type is EST_Dynamic then we have > 0 exception
3913 // types and the exact number is stored in FunctionTypeExtraBitfields.
3914 return EST == EST_Dynamic;
3915 }
3916
3917 /// Whether the trailing FunctionTypeExtraBitfields is present.
3918 bool hasExtraBitfields() const {
3919 return hasExtraBitfields(getExceptionSpecType());
3920 }
3921
3922 bool hasExtQualifiers() const {
3923 return FunctionTypeBits.HasExtQuals;
3924 }
3925
3926public:
3927 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3928
3929 QualType getParamType(unsigned i) const {
3930 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3930, __PRETTY_FUNCTION__))
;
3931 return param_type_begin()[i];
3932 }
3933
3934 ArrayRef<QualType> getParamTypes() const {
3935 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3936 }
3937
3938 ExtProtoInfo getExtProtoInfo() const {
3939 ExtProtoInfo EPI;
3940 EPI.ExtInfo = getExtInfo();
3941 EPI.Variadic = isVariadic();
3942 EPI.HasTrailingReturn = hasTrailingReturn();
3943 EPI.ExceptionSpec.Type = getExceptionSpecType();
3944 EPI.TypeQuals = getMethodQuals();
3945 EPI.RefQualifier = getRefQualifier();
3946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3947 EPI.ExceptionSpec.Exceptions = exceptions();
3948 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3949 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3951 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3952 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3954 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3955 }
3956 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3957 return EPI;
3958 }
3959
3960 /// Get the kind of exception specification on this function.
3961 ExceptionSpecificationType getExceptionSpecType() const {
3962 return static_cast<ExceptionSpecificationType>(
3963 FunctionTypeBits.ExceptionSpecType);
3964 }
3965
3966 /// Return whether this function has any kind of exception spec.
3967 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3968
3969 /// Return whether this function has a dynamic (throw) exception spec.
3970 bool hasDynamicExceptionSpec() const {
3971 return isDynamicExceptionSpec(getExceptionSpecType());
3972 }
3973
3974 /// Return whether this function has a noexcept exception spec.
3975 bool hasNoexceptExceptionSpec() const {
3976 return isNoexceptExceptionSpec(getExceptionSpecType());
3977 }
3978
3979 /// Return whether this function has a dependent exception spec.
3980 bool hasDependentExceptionSpec() const;
3981
3982 /// Return whether this function has an instantiation-dependent exception
3983 /// spec.
3984 bool hasInstantiationDependentExceptionSpec() const;
3985
3986 /// Return the number of types in the exception specification.
3987 unsigned getNumExceptions() const {
3988 return getExceptionSpecType() == EST_Dynamic
3989 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3990 ->NumExceptionType
3991 : 0;
3992 }
3993
3994 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3995 QualType getExceptionType(unsigned i) const {
3996 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3996, __PRETTY_FUNCTION__))
;
3997 return exception_begin()[i];
3998 }
3999
4000 /// Return the expression inside noexcept(expression), or a null pointer
4001 /// if there is none (because the exception spec is not of this form).
4002 Expr *getNoexceptExpr() const {
4003 if (!isComputedNoexcept(getExceptionSpecType()))
4004 return nullptr;
4005 return *getTrailingObjects<Expr *>();
4006 }
4007
4008 /// If this function type has an exception specification which hasn't
4009 /// been determined yet (either because it has not been evaluated or because
4010 /// it has not been instantiated), this is the function whose exception
4011 /// specification is represented by this type.
4012 FunctionDecl *getExceptionSpecDecl() const {
4013 if (getExceptionSpecType() != EST_Uninstantiated &&
4014 getExceptionSpecType() != EST_Unevaluated)
4015 return nullptr;
4016 return getTrailingObjects<FunctionDecl *>()[0];
4017 }
4018
4019 /// If this function type has an uninstantiated exception
4020 /// specification, this is the function whose exception specification
4021 /// should be instantiated to find the exception specification for
4022 /// this type.
4023 FunctionDecl *getExceptionSpecTemplate() const {
4024 if (getExceptionSpecType() != EST_Uninstantiated)
4025 return nullptr;
4026 return getTrailingObjects<FunctionDecl *>()[1];
4027 }
4028
4029 /// Determine whether this function type has a non-throwing exception
4030 /// specification.
4031 CanThrowResult canThrow() const;
4032
4033 /// Determine whether this function type has a non-throwing exception
4034 /// specification. If this depends on template arguments, returns
4035 /// \c ResultIfDependent.
4036 bool isNothrow(bool ResultIfDependent = false) const {
4037 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4038 }
4039
4040 /// Whether this function prototype is variadic.
4041 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4042
4043 /// Determines whether this function prototype contains a
4044 /// parameter pack at the end.
4045 ///
4046 /// A function template whose last parameter is a parameter pack can be
4047 /// called with an arbitrary number of arguments, much like a variadic
4048 /// function.
4049 bool isTemplateVariadic() const;
4050
4051 /// Whether this function prototype has a trailing return type.
4052 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4053
4054 Qualifiers getMethodQuals() const {
4055 if (hasExtQualifiers())
4056 return *getTrailingObjects<Qualifiers>();
4057 else
4058 return getFastTypeQuals();
4059 }
4060
4061 /// Retrieve the ref-qualifier associated with this function type.
4062 RefQualifierKind getRefQualifier() const {
4063 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4064 }
4065
4066 using param_type_iterator = const QualType *;
4067 using param_type_range = llvm::iterator_range<param_type_iterator>;
4068
4069 param_type_range param_types() const {
4070 return param_type_range(param_type_begin(), param_type_end());
4071 }
4072
4073 param_type_iterator param_type_begin() const {
4074 return getTrailingObjects<QualType>();
4075 }
4076
4077 param_type_iterator param_type_end() const {
4078 return param_type_begin() + getNumParams();
4079 }
4080
4081 using exception_iterator = const QualType *;
4082
4083 ArrayRef<QualType> exceptions() const {
4084 return llvm::makeArrayRef(exception_begin(), exception_end());
4085 }
4086
4087 exception_iterator exception_begin() const {
4088 return reinterpret_cast<exception_iterator>(
4089 getTrailingObjects<ExceptionType>());
4090 }
4091
4092 exception_iterator exception_end() const {
4093 return exception_begin() + getNumExceptions();
4094 }
4095
4096 /// Is there any interesting extra information for any of the parameters
4097 /// of this function type?
4098 bool hasExtParameterInfos() const {
4099 return FunctionTypeBits.HasExtParameterInfos;
4100 }
4101
4102 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4103 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4103, __PRETTY_FUNCTION__))
;
4104 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4105 getNumParams());
4106 }
4107
4108 /// Return a pointer to the beginning of the array of extra parameter
4109 /// information, if present, or else null if none of the parameters
4110 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4111 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4112 if (!hasExtParameterInfos())
4113 return nullptr;
4114 return getTrailingObjects<ExtParameterInfo>();
4115 }
4116
4117 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4118 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4118, __PRETTY_FUNCTION__))
;
4119 if (hasExtParameterInfos())
4120 return getTrailingObjects<ExtParameterInfo>()[I];
4121 return ExtParameterInfo();
4122 }
4123
4124 ParameterABI getParameterABI(unsigned I) const {
4125 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4125, __PRETTY_FUNCTION__))
;
4126 if (hasExtParameterInfos())
4127 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4128 return ParameterABI::Ordinary;
4129 }
4130
4131 bool isParamConsumed(unsigned I) const {
4132 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 if (hasExtParameterInfos())
4134 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4135 return false;
4136 }
4137
4138 bool isSugared() const { return false; }
4139 QualType desugar() const { return QualType(this, 0); }
4140
4141 void printExceptionSpecification(raw_ostream &OS,
4142 const PrintingPolicy &Policy) const;
4143
4144 static bool classof(const Type *T) {
4145 return T->getTypeClass() == FunctionProto;
4146 }
4147
4148 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4149 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4150 param_type_iterator ArgTys, unsigned NumArgs,
4151 const ExtProtoInfo &EPI, const ASTContext &Context,
4152 bool Canonical);
4153};
4154
4155/// Represents the dependent type named by a dependently-scoped
4156/// typename using declaration, e.g.
4157/// using typename Base<T>::foo;
4158///
4159/// Template instantiation turns these into the underlying type.
4160class UnresolvedUsingType : public Type {
4161 friend class ASTContext; // ASTContext creates these.
4162
4163 UnresolvedUsingTypenameDecl *Decl;
4164
4165 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4166 : Type(UnresolvedUsing, QualType(), true, true, false,
4167 /*ContainsUnexpandedParameterPack=*/false),
4168 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4169
4170public:
4171 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4172
4173 bool isSugared() const { return false; }
4174 QualType desugar() const { return QualType(this, 0); }
4175
4176 static bool classof(const Type *T) {
4177 return T->getTypeClass() == UnresolvedUsing;
4178 }
4179
4180 void Profile(llvm::FoldingSetNodeID &ID) {
4181 return Profile(ID, Decl);
4182 }
4183
4184 static void Profile(llvm::FoldingSetNodeID &ID,
4185 UnresolvedUsingTypenameDecl *D) {
4186 ID.AddPointer(D);
4187 }
4188};
4189
4190class TypedefType : public Type {
4191 TypedefNameDecl *Decl;
4192
4193protected:
4194 friend class ASTContext; // ASTContext creates these.
4195
4196 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4197 : Type(tc, can, can->isDependentType(),
4198 can->isInstantiationDependentType(),
4199 can->isVariablyModifiedType(),
4200 /*ContainsUnexpandedParameterPack=*/false),
4201 Decl(const_cast<TypedefNameDecl*>(D)) {
4202 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4202, __PRETTY_FUNCTION__))
;
4203 }
4204
4205public:
4206 TypedefNameDecl *getDecl() const { return Decl; }
4207
4208 bool isSugared() const { return true; }
4209 QualType desugar() const;
4210
4211 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4212};
4213
4214/// Sugar type that represents a type that was qualified by a qualifier written
4215/// as a macro invocation.
4216class MacroQualifiedType : public Type {
4217 friend class ASTContext; // ASTContext creates these.
4218
4219 QualType UnderlyingTy;
4220 const IdentifierInfo *MacroII;
4221
4222 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4223 const IdentifierInfo *MacroII)
4224 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4225 UnderlyingTy->isInstantiationDependentType(),
4226 UnderlyingTy->isVariablyModifiedType(),
4227 UnderlyingTy->containsUnexpandedParameterPack()),
4228 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4229 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
4230 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
;
4231 }
4232
4233public:
4234 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4235 QualType getUnderlyingType() const { return UnderlyingTy; }
4236
4237 /// Return this attributed type's modified type with no qualifiers attached to
4238 /// it.
4239 QualType getModifiedType() const;
4240
4241 bool isSugared() const { return true; }
4242 QualType desugar() const;
4243
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == MacroQualified;
4246 }
4247};
4248
4249/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4250class TypeOfExprType : public Type {
4251 Expr *TOExpr;
4252
4253protected:
4254 friend class ASTContext; // ASTContext creates these.
4255
4256 TypeOfExprType(Expr *E, QualType can = QualType());
4257
4258public:
4259 Expr *getUnderlyingExpr() const { return TOExpr; }
4260
4261 /// Remove a single level of sugar.
4262 QualType desugar() const;
4263
4264 /// Returns whether this type directly provides sugar.
4265 bool isSugared() const;
4266
4267 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4268};
4269
4270/// Internal representation of canonical, dependent
4271/// `typeof(expr)` types.
4272///
4273/// This class is used internally by the ASTContext to manage
4274/// canonical, dependent types, only. Clients will only see instances
4275/// of this class via TypeOfExprType nodes.
4276class DependentTypeOfExprType
4277 : public TypeOfExprType, public llvm::FoldingSetNode {
4278 const ASTContext &Context;
4279
4280public:
4281 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4282 : TypeOfExprType(E), Context(Context) {}
4283
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, Context, getUnderlyingExpr());
4286 }
4287
4288 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4289 Expr *E);
4290};
4291
4292/// Represents `typeof(type)`, a GCC extension.
4293class TypeOfType : public Type {
4294 friend class ASTContext; // ASTContext creates these.
4295
4296 QualType TOType;
4297
4298 TypeOfType(QualType T, QualType can)
4299 : Type(TypeOf, can, T->isDependentType(),
4300 T->isInstantiationDependentType(),
4301 T->isVariablyModifiedType(),
4302 T->containsUnexpandedParameterPack()),
4303 TOType(T) {
4304 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4304, __PRETTY_FUNCTION__))
;
4305 }
4306
4307public:
4308 QualType getUnderlyingType() const { return TOType; }
4309
4310 /// Remove a single level of sugar.
4311 QualType desugar() const { return getUnderlyingType(); }
4312
4313 /// Returns whether this type directly provides sugar.
4314 bool isSugared() const { return true; }
4315
4316 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4317};
4318
4319/// Represents the type `decltype(expr)` (C++11).
4320class DecltypeType : public Type {
4321 Expr *E;
4322 QualType UnderlyingType;
4323
4324protected:
4325 friend class ASTContext; // ASTContext creates these.
4326
4327 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4328
4329public:
4330 Expr *getUnderlyingExpr() const { return E; }
4331 QualType getUnderlyingType() const { return UnderlyingType; }
4332
4333 /// Remove a single level of sugar.
4334 QualType desugar() const;
4335
4336 /// Returns whether this type directly provides sugar.
4337 bool isSugared() const;
4338
4339 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4340};
4341
4342/// Internal representation of canonical, dependent
4343/// decltype(expr) types.
4344///
4345/// This class is used internally by the ASTContext to manage
4346/// canonical, dependent types, only. Clients will only see instances
4347/// of this class via DecltypeType nodes.
4348class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4349 const ASTContext &Context;
4350
4351public:
4352 DependentDecltypeType(const ASTContext &Context, Expr *E);
4353
4354 void Profile(llvm::FoldingSetNodeID &ID) {
4355 Profile(ID, Context, getUnderlyingExpr());
4356 }
4357
4358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4359 Expr *E);
4360};
4361
4362/// A unary type transform, which is a type constructed from another.
4363class UnaryTransformType : public Type {
4364public:
4365 enum UTTKind {
4366 EnumUnderlyingType
4367 };
4368
4369private:
4370 /// The untransformed type.
4371 QualType BaseType;
4372
4373 /// The transformed type if not dependent, otherwise the same as BaseType.
4374 QualType UnderlyingType;
4375
4376 UTTKind UKind;
4377
4378protected:
4379 friend class ASTContext;
4380
4381 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4382 QualType CanonicalTy);
4383
4384public:
4385 bool isSugared() const { return !isDependentType(); }
4386 QualType desugar() const { return UnderlyingType; }
4387
4388 QualType getUnderlyingType() const { return UnderlyingType; }
4389 QualType getBaseType() const { return BaseType; }
4390
4391 UTTKind getUTTKind() const { return UKind; }
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == UnaryTransform;
4395 }
4396};
4397
4398/// Internal representation of canonical, dependent
4399/// __underlying_type(type) types.
4400///
4401/// This class is used internally by the ASTContext to manage
4402/// canonical, dependent types, only. Clients will only see instances
4403/// of this class via UnaryTransformType nodes.
4404class DependentUnaryTransformType : public UnaryTransformType,
4405 public llvm::FoldingSetNode {
4406public:
4407 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4408 UTTKind UKind);
4409
4410 void Profile(llvm::FoldingSetNodeID &ID) {
4411 Profile(ID, getBaseType(), getUTTKind());
4412 }
4413
4414 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4415 UTTKind UKind) {
4416 ID.AddPointer(BaseType.getAsOpaquePtr());
4417 ID.AddInteger((unsigned)UKind);
4418 }
4419};
4420
4421class TagType : public Type {
4422 friend class ASTReader;
4423
4424 /// Stores the TagDecl associated with this type. The decl may point to any
4425 /// TagDecl that declares the entity.
4426 TagDecl *decl;
4427
4428protected:
4429 TagType(TypeClass TC, const TagDecl *D, QualType can);
4430
4431public:
4432 TagDecl *getDecl() const;
4433
4434 /// Determines whether this type is in the process of being defined.
4435 bool isBeingDefined() const;
4436
4437 static bool classof(const Type *T) {
4438 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4439 }
4440};
4441
4442/// A helper class that allows the use of isa/cast/dyncast
4443/// to detect TagType objects of structs/unions/classes.
4444class RecordType : public TagType {
4445protected:
4446 friend class ASTContext; // ASTContext creates these.
4447
4448 explicit RecordType(const RecordDecl *D)
4449 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4450 explicit RecordType(TypeClass TC, RecordDecl *D)
4451 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4452
4453public:
4454 RecordDecl *getDecl() const {
4455 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4456 }
4457
4458 /// Recursively check all fields in the record for const-ness. If any field
4459 /// is declared const, return true. Otherwise, return false.
4460 bool hasConstFields() const;
4461
4462 bool isSugared() const { return false; }
4463 QualType desugar() const { return QualType(this, 0); }
4464
4465 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4466};
4467
4468/// A helper class that allows the use of isa/cast/dyncast
4469/// to detect TagType objects of enums.
4470class EnumType : public TagType {
4471 friend class ASTContext; // ASTContext creates these.
4472
4473 explicit EnumType(const EnumDecl *D)
4474 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4475
4476public:
4477 EnumDecl *getDecl() const {
4478 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4479 }
4480
4481 bool isSugared() const { return false; }
4482 QualType desugar() const { return QualType(this, 0); }
4483
4484 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4485};
4486
4487/// An attributed type is a type to which a type attribute has been applied.
4488///
4489/// The "modified type" is the fully-sugared type to which the attributed
4490/// type was applied; generally it is not canonically equivalent to the
4491/// attributed type. The "equivalent type" is the minimally-desugared type
4492/// which the type is canonically equivalent to.
4493///
4494/// For example, in the following attributed type:
4495/// int32_t __attribute__((vector_size(16)))
4496/// - the modified type is the TypedefType for int32_t
4497/// - the equivalent type is VectorType(16, int32_t)
4498/// - the canonical type is VectorType(16, int)
4499class AttributedType : public Type, public llvm::FoldingSetNode {
4500public:
4501 using Kind = attr::Kind;
4502
4503private:
4504 friend class ASTContext; // ASTContext creates these
4505
4506 QualType ModifiedType;
4507 QualType EquivalentType;
4508
4509 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4510 QualType equivalent)
4511 : Type(Attributed, canon, equivalent->isDependentType(),
4512 equivalent->isInstantiationDependentType(),
4513 equivalent->isVariablyModifiedType(),
4514 equivalent->containsUnexpandedParameterPack()),
4515 ModifiedType(modified), EquivalentType(equivalent) {
4516 AttributedTypeBits.AttrKind = attrKind;
4517 }
4518
4519public:
4520 Kind getAttrKind() const {
4521 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4522 }
4523
4524 QualType getModifiedType() const { return ModifiedType; }
4525 QualType getEquivalentType() const { return EquivalentType; }
4526
4527 bool isSugared() const { return true; }
4528 QualType desugar() const { return getEquivalentType(); }
4529
4530 /// Does this attribute behave like a type qualifier?
4531 ///
4532 /// A type qualifier adjusts a type to provide specialized rules for
4533 /// a specific object, like the standard const and volatile qualifiers.
4534 /// This includes attributes controlling things like nullability,
4535 /// address spaces, and ARC ownership. The value of the object is still
4536 /// largely described by the modified type.
4537 ///
4538 /// In contrast, many type attributes "rewrite" their modified type to
4539 /// produce a fundamentally different type, not necessarily related in any
4540 /// formalizable way to the original type. For example, calling convention
4541 /// and vector attributes are not simple type qualifiers.
4542 ///
4543 /// Type qualifiers are often, but not always, reflected in the canonical
4544 /// type.
4545 bool isQualifier() const;
4546
4547 bool isMSTypeSpec() const;
4548
4549 bool isCallingConv() const;
4550
4551 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4552
4553 /// Retrieve the attribute kind corresponding to the given
4554 /// nullability kind.
4555 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4556 switch (kind) {
4557 case NullabilityKind::NonNull:
4558 return attr::TypeNonNull;
4559
4560 case NullabilityKind::Nullable:
4561 return attr::TypeNullable;
4562
4563 case NullabilityKind::Unspecified:
4564 return attr::TypeNullUnspecified;
4565 }
4566 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4566)
;
4567 }
4568
4569 /// Strip off the top-level nullability annotation on the given
4570 /// type, if it's there.
4571 ///
4572 /// \param T The type to strip. If the type is exactly an
4573 /// AttributedType specifying nullability (without looking through
4574 /// type sugar), the nullability is returned and this type changed
4575 /// to the underlying modified type.
4576 ///
4577 /// \returns the top-level nullability, if present.
4578 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4585 QualType modified, QualType equivalent) {
4586 ID.AddInteger(attrKind);
4587 ID.AddPointer(modified.getAsOpaquePtr());
4588 ID.AddPointer(equivalent.getAsOpaquePtr());
4589 }
4590
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Attributed;
4593 }
4594};
4595
4596class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4597 friend class ASTContext; // ASTContext creates these
4598
4599 // Helper data collector for canonical types.
4600 struct CanonicalTTPTInfo {
4601 unsigned Depth : 15;
4602 unsigned ParameterPack : 1;
4603 unsigned Index : 16;
4604 };
4605
4606 union {
4607 // Info for the canonical type.
4608 CanonicalTTPTInfo CanTTPTInfo;
4609
4610 // Info for the non-canonical type.
4611 TemplateTypeParmDecl *TTPDecl;
4612 };
4613
4614 /// Build a non-canonical type.
4615 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4616 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4617 /*InstantiationDependent=*/true,
4618 /*VariablyModified=*/false,
4619 Canon->containsUnexpandedParameterPack()),
4620 TTPDecl(TTPDecl) {}
4621
4622 /// Build the canonical type.
4623 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4624 : Type(TemplateTypeParm, QualType(this, 0),
4625 /*Dependent=*/true,
4626 /*InstantiationDependent=*/true,
4627 /*VariablyModified=*/false, PP) {
4628 CanTTPTInfo.Depth = D;
4629 CanTTPTInfo.Index = I;
4630 CanTTPTInfo.ParameterPack = PP;
4631 }
4632
4633 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4634 QualType Can = getCanonicalTypeInternal();
4635 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4636 }
4637
4638public:
4639 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4640 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4641 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4642
4643 TemplateTypeParmDecl *getDecl() const {
4644 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4645 }
4646
4647 IdentifierInfo *getIdentifier() const;
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 void Profile(llvm::FoldingSetNodeID &ID) {
4653 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4654 }
4655
4656 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4657 unsigned Index, bool ParameterPack,
4658 TemplateTypeParmDecl *TTPDecl) {
4659 ID.AddInteger(Depth);
4660 ID.AddInteger(Index);
4661 ID.AddBoolean(ParameterPack);
4662 ID.AddPointer(TTPDecl);
4663 }
4664
4665 static bool classof(const Type *T) {
4666 return T->getTypeClass() == TemplateTypeParm;
4667 }
4668};
4669
4670/// Represents the result of substituting a type for a template
4671/// type parameter.
4672///
4673/// Within an instantiated template, all template type parameters have
4674/// been replaced with these. They are used solely to record that a
4675/// type was originally written as a template type parameter;
4676/// therefore they are never canonical.
4677class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4678 friend class ASTContext;
4679
4680 // The original type parameter.
4681 const TemplateTypeParmType *Replaced;
4682
4683 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4684 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4685 Canon->isInstantiationDependentType(),
4686 Canon->isVariablyModifiedType(),
4687 Canon->containsUnexpandedParameterPack()),
4688 Replaced(Param) {}
4689
4690public:
4691 /// Gets the template parameter that was substituted for.
4692 const TemplateTypeParmType *getReplacedParameter() const {
4693 return Replaced;
4694 }
4695
4696 /// Gets the type that was substituted for the template
4697 /// parameter.
4698 QualType getReplacementType() const {
4699 return getCanonicalTypeInternal();
4700 }
4701
4702 bool isSugared() const { return true; }
4703 QualType desugar() const { return getReplacementType(); }
4704
4705 void Profile(llvm::FoldingSetNodeID &ID) {
4706 Profile(ID, getReplacedParameter(), getReplacementType());
4707 }
4708
4709 static void Profile(llvm::FoldingSetNodeID &ID,
4710 const TemplateTypeParmType *Replaced,
4711 QualType Replacement) {
4712 ID.AddPointer(Replaced);
4713 ID.AddPointer(Replacement.getAsOpaquePtr());
4714 }
4715
4716 static bool classof(const Type *T) {
4717 return T->getTypeClass() == SubstTemplateTypeParm;
4718 }
4719};
4720
4721/// Represents the result of substituting a set of types for a template
4722/// type parameter pack.
4723///
4724/// When a pack expansion in the source code contains multiple parameter packs
4725/// and those parameter packs correspond to different levels of template
4726/// parameter lists, this type node is used to represent a template type
4727/// parameter pack from an outer level, which has already had its argument pack
4728/// substituted but that still lives within a pack expansion that itself
4729/// could not be instantiated. When actually performing a substitution into
4730/// that pack expansion (e.g., when all template parameters have corresponding
4731/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4732/// at the current pack substitution index.
4733class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4734 friend class ASTContext;
4735
4736 /// The original type parameter.
4737 const TemplateTypeParmType *Replaced;
4738
4739 /// A pointer to the set of template arguments that this
4740 /// parameter pack is instantiated with.
4741 const TemplateArgument *Arguments;
4742
4743 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4744 QualType Canon,
4745 const TemplateArgument &ArgPack);
4746
4747public:
4748 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4749
4750 /// Gets the template parameter that was substituted for.
4751 const TemplateTypeParmType *getReplacedParameter() const {
4752 return Replaced;
4753 }
4754
4755 unsigned getNumArgs() const {
4756 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4757 }
4758
4759 bool isSugared() const { return false; }
4760 QualType desugar() const { return QualType(this, 0); }
4761
4762 TemplateArgument getArgumentPack() const;
4763
4764 void Profile(llvm::FoldingSetNodeID &ID);
4765 static void Profile(llvm::FoldingSetNodeID &ID,
4766 const TemplateTypeParmType *Replaced,
4767 const TemplateArgument &ArgPack);
4768
4769 static bool classof(const Type *T) {
4770 return T->getTypeClass() == SubstTemplateTypeParmPack;
4771 }
4772};
4773
4774/// Common base class for placeholders for types that get replaced by
4775/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4776/// class template types, and (eventually) constrained type names from the C++
4777/// Concepts TS.
4778///
4779/// These types are usually a placeholder for a deduced type. However, before
4780/// the initializer is attached, or (usually) if the initializer is
4781/// type-dependent, there is no deduced type and the type is canonical. In
4782/// the latter case, it is also a dependent type.
4783class DeducedType : public Type {
4784protected:
4785 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4786 bool IsInstantiationDependent, bool ContainsParameterPack)
4787 : Type(TC,
4788 // FIXME: Retain the sugared deduced type?
4789 DeducedAsType.isNull() ? QualType(this, 0)
4790 : DeducedAsType.getCanonicalType(),
4791 IsDependent, IsInstantiationDependent,
4792 /*VariablyModified=*/false, ContainsParameterPack) {
4793 if (!DeducedAsType.isNull()) {
4794 if (DeducedAsType->isDependentType())
4795 setDependent();
4796 if (DeducedAsType->isInstantiationDependentType())
4797 setInstantiationDependent();
4798 if (DeducedAsType->containsUnexpandedParameterPack())
4799 setContainsUnexpandedParameterPack();
4800 }
4801 }
4802
4803public:
4804 bool isSugared() const { return !isCanonicalUnqualified(); }
4805 QualType desugar() const { return getCanonicalTypeInternal(); }
4806
4807 /// Get the type deduced for this placeholder type, or null if it's
4808 /// either not been deduced or was deduced to a dependent type.
4809 QualType getDeducedType() const {
4810 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4811 }
4812 bool isDeduced() const {
4813 return !isCanonicalUnqualified() || isDependentType();
4814 }
4815
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == Auto ||
4818 T->getTypeClass() == DeducedTemplateSpecialization;
4819 }
4820};
4821
4822/// Represents a C++11 auto or C++14 decltype(auto) type.
4823class AutoType : public DeducedType, public llvm::FoldingSetNode {
4824 friend class ASTContext; // ASTContext creates these
4825
4826 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4827 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4828 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4829 IsDeducedAsDependent, IsDeducedAsPack) {
4830 AutoTypeBits.Keyword = (unsigned)Keyword;
4831 }
4832
4833public:
4834 bool isDecltypeAuto() const {
4835 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4836 }
4837
4838 AutoTypeKeyword getKeyword() const {
4839 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4840 }
4841
4842 void Profile(llvm::FoldingSetNodeID &ID) {
4843 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4844 containsUnexpandedParameterPack());
4845 }
4846
4847 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4848 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4849 ID.AddPointer(Deduced.getAsOpaquePtr());
4850 ID.AddInteger((unsigned)Keyword);
4851 ID.AddBoolean(IsDependent);
4852 ID.AddBoolean(IsPack);
4853 }
4854
4855 static bool classof(const Type *T) {
4856 return T->getTypeClass() == Auto;
4857 }
4858};
4859
4860/// Represents a C++17 deduced template specialization type.
4861class DeducedTemplateSpecializationType : public DeducedType,
4862 public llvm::FoldingSetNode {
4863 friend class ASTContext; // ASTContext creates these
4864
4865 /// The name of the template whose arguments will be deduced.
4866 TemplateName Template;
4867
4868 DeducedTemplateSpecializationType(TemplateName Template,
4869 QualType DeducedAsType,
4870 bool IsDeducedAsDependent)
4871 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4872 IsDeducedAsDependent || Template.isDependent(),
4873 IsDeducedAsDependent || Template.isInstantiationDependent(),
4874 Template.containsUnexpandedParameterPack()),
4875 Template(Template) {}
4876
4877public:
4878 /// Retrieve the name of the template that we are deducing.
4879 TemplateName getTemplateName() const { return Template;}
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4886 QualType Deduced, bool IsDependent) {
4887 Template.Profile(ID);
4888 ID.AddPointer(Deduced.getAsOpaquePtr());
4889 ID.AddBoolean(IsDependent);
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == DeducedTemplateSpecialization;
4894 }
4895};
4896
4897/// Represents a type template specialization; the template
4898/// must be a class template, a type alias template, or a template
4899/// template parameter. A template which cannot be resolved to one of
4900/// these, e.g. because it is written with a dependent scope
4901/// specifier, is instead represented as a
4902/// @c DependentTemplateSpecializationType.
4903///
4904/// A non-dependent template specialization type is always "sugar",
4905/// typically for a \c RecordType. For example, a class template
4906/// specialization type of \c vector<int> will refer to a tag type for
4907/// the instantiation \c std::vector<int, std::allocator<int>>
4908///
4909/// Template specializations are dependent if either the template or
4910/// any of the template arguments are dependent, in which case the
4911/// type may also be canonical.
4912///
4913/// Instances of this type are allocated with a trailing array of
4914/// TemplateArguments, followed by a QualType representing the
4915/// non-canonical aliased type when the template is a type alias
4916/// template.
4917class alignas(8) TemplateSpecializationType
4918 : public Type,
4919 public llvm::FoldingSetNode {
4920 friend class ASTContext; // ASTContext creates these
4921
4922 /// The name of the template being specialized. This is
4923 /// either a TemplateName::Template (in which case it is a
4924 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4925 /// TypeAliasTemplateDecl*), a
4926 /// TemplateName::SubstTemplateTemplateParmPack, or a
4927 /// TemplateName::SubstTemplateTemplateParm (in which case the
4928 /// replacement must, recursively, be one of these).
4929 TemplateName Template;
4930
4931 TemplateSpecializationType(TemplateName T,
4932 ArrayRef<TemplateArgument> Args,
4933 QualType Canon,
4934 QualType Aliased);
4935
4936public:
4937 /// Determine whether any of the given template arguments are dependent.
4938 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4939 bool &InstantiationDependent);
4940
4941 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4942 bool &InstantiationDependent);
4943
4944 /// True if this template specialization type matches a current
4945 /// instantiation in the context in which it is found.
4946 bool isCurrentInstantiation() const {
4947 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4948 }
4949
4950 /// Determine if this template specialization type is for a type alias
4951 /// template that has been substituted.
4952 ///
4953 /// Nearly every template specialization type whose template is an alias
4954 /// template will be substituted. However, this is not the case when
4955 /// the specialization contains a pack expansion but the template alias
4956 /// does not have a corresponding parameter pack, e.g.,
4957 ///
4958 /// \code
4959 /// template<typename T, typename U, typename V> struct S;
4960 /// template<typename T, typename U> using A = S<T, int, U>;
4961 /// template<typename... Ts> struct X {
4962 /// typedef A<Ts...> type; // not a type alias
4963 /// };
4964 /// \endcode
4965 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4966
4967 /// Get the aliased type, if this is a specialization of a type alias
4968 /// template.
4969 QualType getAliasedType() const {
4970 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4970, __PRETTY_FUNCTION__))
;
4971 return *reinterpret_cast<const QualType*>(end());
4972 }
4973
4974 using iterator = const TemplateArgument *;
4975
4976 iterator begin() const { return getArgs(); }
4977 iterator end() const; // defined inline in TemplateBase.h
4978
4979 /// Retrieve the name of the template that we are specializing.
4980 TemplateName getTemplateName() const { return Template; }
4981
4982 /// Retrieve the template arguments.
4983 const TemplateArgument *getArgs() const {
4984 return reinterpret_cast<const TemplateArgument *>(this + 1);
4985 }
4986
4987 /// Retrieve the number of template arguments.
4988 unsigned getNumArgs() const {
4989 return TemplateSpecializationTypeBits.NumArgs;
4990 }
4991
4992 /// Retrieve a specific template argument as a type.
4993 /// \pre \c isArgType(Arg)
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> template_arguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 bool isSugared() const {
5001 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5002 }
5003
5004 QualType desugar() const {
5005 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5006 }
5007
5008 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5009 Profile(ID, Template, template_arguments(), Ctx);
5010 if (isTypeAlias())
5011 getAliasedType().Profile(ID);
5012 }
5013
5014 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5015 ArrayRef<TemplateArgument> Args,
5016 const ASTContext &Context);
5017
5018 static bool classof(const Type *T) {
5019 return T->getTypeClass() == TemplateSpecialization;
5020 }
5021};
5022
5023/// Print a template argument list, including the '<' and '>'
5024/// enclosing the template arguments.
5025void printTemplateArgumentList(raw_ostream &OS,
5026 ArrayRef<TemplateArgument> Args,
5027 const PrintingPolicy &Policy);
5028
5029void printTemplateArgumentList(raw_ostream &OS,
5030 ArrayRef<TemplateArgumentLoc> Args,
5031 const PrintingPolicy &Policy);
5032
5033void printTemplateArgumentList(raw_ostream &OS,
5034 const TemplateArgumentListInfo &Args,
5035 const PrintingPolicy &Policy);
5036
5037/// The injected class name of a C++ class template or class
5038/// template partial specialization. Used to record that a type was
5039/// spelled with a bare identifier rather than as a template-id; the
5040/// equivalent for non-templated classes is just RecordType.
5041///
5042/// Injected class name types are always dependent. Template
5043/// instantiation turns these into RecordTypes.
5044///
5045/// Injected class name types are always canonical. This works
5046/// because it is impossible to compare an injected class name type
5047/// with the corresponding non-injected template type, for the same
5048/// reason that it is impossible to directly compare template
5049/// parameters from different dependent contexts: injected class name
5050/// types can only occur within the scope of a particular templated
5051/// declaration, and within that scope every template specialization
5052/// will canonicalize to the injected class name (when appropriate
5053/// according to the rules of the language).
5054class InjectedClassNameType : public Type {
5055 friend class ASTContext; // ASTContext creates these.
5056 friend class ASTNodeImporter;
5057 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5058 // currently suitable for AST reading, too much
5059 // interdependencies.
5060
5061 CXXRecordDecl *Decl;
5062
5063 /// The template specialization which this type represents.
5064 /// For example, in
5065 /// template <class T> class A { ... };
5066 /// this is A<T>, whereas in
5067 /// template <class X, class Y> class A<B<X,Y> > { ... };
5068 /// this is A<B<X,Y> >.
5069 ///
5070 /// It is always unqualified, always a template specialization type,
5071 /// and always dependent.
5072 QualType InjectedType;
5073
5074 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5075 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5076 /*InstantiationDependent=*/true,
5077 /*VariablyModified=*/false,
5078 /*ContainsUnexpandedParameterPack=*/false),
5079 Decl(D), InjectedType(TST) {
5080 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5080, __PRETTY_FUNCTION__))
;
5081 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5081, __PRETTY_FUNCTION__))
;
5082 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5082, __PRETTY_FUNCTION__))
;
5083 }
5084
5085public:
5086 QualType getInjectedSpecializationType() const { return InjectedType; }
5087
5088 const TemplateSpecializationType *getInjectedTST() const {
5089 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5090 }
5091
5092 TemplateName getTemplateName() const {
5093 return getInjectedTST()->getTemplateName();
5094 }
5095
5096 CXXRecordDecl *getDecl() const;
5097
5098 bool isSugared() const { return false; }
5099 QualType desugar() const { return QualType(this, 0); }
5100
5101 static bool classof(const Type *T) {
5102 return T->getTypeClass() == InjectedClassName;
5103 }
5104};
5105
5106/// The kind of a tag type.
5107enum TagTypeKind {
5108 /// The "struct" keyword.
5109 TTK_Struct,
5110
5111 /// The "__interface" keyword.
5112 TTK_Interface,
5113
5114 /// The "union" keyword.
5115 TTK_Union,
5116
5117 /// The "class" keyword.
5118 TTK_Class,
5119
5120 /// The "enum" keyword.
5121 TTK_Enum
5122};
5123
5124/// The elaboration keyword that precedes a qualified type name or
5125/// introduces an elaborated-type-specifier.
5126enum ElaboratedTypeKeyword {
5127 /// The "struct" keyword introduces the elaborated-type-specifier.
5128 ETK_Struct,
5129
5130 /// The "__interface" keyword introduces the elaborated-type-specifier.
5131 ETK_Interface,
5132
5133 /// The "union" keyword introduces the elaborated-type-specifier.
5134 ETK_Union,
5135
5136 /// The "class" keyword introduces the elaborated-type-specifier.
5137 ETK_Class,
5138
5139 /// The "enum" keyword introduces the elaborated-type-specifier.
5140 ETK_Enum,
5141
5142 /// The "typename" keyword precedes the qualified type name, e.g.,
5143 /// \c typename T::type.
5144 ETK_Typename,
5145
5146 /// No keyword precedes the qualified type name.
5147 ETK_None
5148};
5149
5150/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5151/// The keyword in stored in the free bits of the base class.
5152/// Also provides a few static helpers for converting and printing
5153/// elaborated type keyword and tag type kind enumerations.
5154class TypeWithKeyword : public Type {
5155protected:
5156 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5157 QualType Canonical, bool Dependent,
5158 bool InstantiationDependent, bool VariablyModified,
5159 bool ContainsUnexpandedParameterPack)
5160 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5161 ContainsUnexpandedParameterPack) {
5162 TypeWithKeywordBits.Keyword = Keyword;
5163 }
5164
5165public:
5166 ElaboratedTypeKeyword getKeyword() const {
5167 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5168 }
5169
5170 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5171 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5172
5173 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5174 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5175 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5176
5177 /// Converts a TagTypeKind into an elaborated type keyword.
5178 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5179
5180 /// Converts an elaborated type keyword into a TagTypeKind.
5181 /// It is an error to provide an elaborated type keyword
5182 /// which *isn't* a tag kind here.
5183 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5184
5185 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5186
5187 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5188
5189 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5190 return getKeywordName(getKeywordForTagTypeKind(Kind));
5191 }
5192
5193 class CannotCastToThisType {};
5194 static CannotCastToThisType classof(const Type *);
5195};
5196
5197/// Represents a type that was referred to using an elaborated type
5198/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5199/// or both.
5200///
5201/// This type is used to keep track of a type name as written in the
5202/// source code, including tag keywords and any nested-name-specifiers.
5203/// The type itself is always "sugar", used to express what was written
5204/// in the source code but containing no additional semantic information.
5205class ElaboratedType final
5206 : public TypeWithKeyword,
5207 public llvm::FoldingSetNode,
5208 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5209 friend class ASTContext; // ASTContext creates these
5210 friend TrailingObjects;
5211
5212 /// The nested name specifier containing the qualifier.
5213 NestedNameSpecifier *NNS;
5214
5215 /// The type that this qualified name refers to.
5216 QualType NamedType;
5217
5218 /// The (re)declaration of this tag type owned by this occurrence is stored
5219 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5220 /// it, or obtain a null pointer if there is none.
5221
5222 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5223 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5224 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5225 NamedType->isDependentType(),
5226 NamedType->isInstantiationDependentType(),
5227 NamedType->isVariablyModifiedType(),
5228 NamedType->containsUnexpandedParameterPack()),
5229 NNS(NNS), NamedType(NamedType) {
5230 ElaboratedTypeBits.HasOwnedTagDecl = false;
5231 if (OwnedTagDecl) {
5232 ElaboratedTypeBits.HasOwnedTagDecl = true;
5233 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5234 }
5235 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5236 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5237 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
;
5238 }
5239
5240public:
5241 /// Retrieve the qualification on this type.
5242 NestedNameSpecifier *getQualifier() const { return NNS; }
5243
5244 /// Retrieve the type named by the qualified-id.
5245 QualType getNamedType() const { return NamedType; }
5246
5247 /// Remove a single level of sugar.
5248 QualType desugar() const { return getNamedType(); }
5249
5250 /// Returns whether this type directly provides sugar.
5251 bool isSugared() const { return true; }
5252
5253 /// Return the (re)declaration of this type owned by this occurrence of this
5254 /// type, or nullptr if there is none.
5255 TagDecl *getOwnedTagDecl() const {
5256 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5257 : nullptr;
5258 }
5259
5260 void Profile(llvm::FoldingSetNodeID &ID) {
5261 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5262 }
5263
5264 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5265 NestedNameSpecifier *NNS, QualType NamedType,
5266 TagDecl *OwnedTagDecl) {
5267 ID.AddInteger(Keyword);
5268 ID.AddPointer(NNS);
5269 NamedType.Profile(ID);
5270 ID.AddPointer(OwnedTagDecl);
5271 }
5272
5273 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5274};
5275
5276/// Represents a qualified type name for which the type name is
5277/// dependent.
5278///
5279/// DependentNameType represents a class of dependent types that involve a
5280/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5281/// name of a type. The DependentNameType may start with a "typename" (for a
5282/// typename-specifier), "class", "struct", "union", or "enum" (for a
5283/// dependent elaborated-type-specifier), or nothing (in contexts where we
5284/// know that we must be referring to a type, e.g., in a base class specifier).
5285/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5286/// mode, this type is used with non-dependent names to delay name lookup until
5287/// instantiation.
5288class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5289 friend class ASTContext; // ASTContext creates these
5290
5291 /// The nested name specifier containing the qualifier.
5292 NestedNameSpecifier *NNS;
5293
5294 /// The type that this typename specifier refers to.
5295 const IdentifierInfo *Name;
5296
5297 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5298 const IdentifierInfo *Name, QualType CanonType)
5299 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5300 /*InstantiationDependent=*/true,
5301 /*VariablyModified=*/false,
5302 NNS->containsUnexpandedParameterPack()),
5303 NNS(NNS), Name(Name) {}
5304
5305public:
5306 /// Retrieve the qualification on this type.
5307 NestedNameSpecifier *getQualifier() const { return NNS; }
5308
5309 /// Retrieve the type named by the typename specifier as an identifier.
5310 ///
5311 /// This routine will return a non-NULL identifier pointer when the
5312 /// form of the original typename was terminated by an identifier,
5313 /// e.g., "typename T::type".
5314 const IdentifierInfo *getIdentifier() const {
5315 return Name;
5316 }
5317
5318 bool isSugared() const { return false; }
5319 QualType desugar() const { return QualType(this, 0); }
5320
5321 void Profile(llvm::FoldingSetNodeID &ID) {
5322 Profile(ID, getKeyword(), NNS, Name);
5323 }
5324
5325 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5326 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5327 ID.AddInteger(Keyword);
5328 ID.AddPointer(NNS);
5329 ID.AddPointer(Name);
5330 }
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == DependentName;
5334 }
5335};
5336
5337/// Represents a template specialization type whose template cannot be
5338/// resolved, e.g.
5339/// A<T>::template B<T>
5340class alignas(8) DependentTemplateSpecializationType
5341 : public TypeWithKeyword,
5342 public llvm::FoldingSetNode {
5343 friend class ASTContext; // ASTContext creates these
5344
5345 /// The nested name specifier containing the qualifier.
5346 NestedNameSpecifier *NNS;
5347
5348 /// The identifier of the template.
5349 const IdentifierInfo *Name;
5350
5351 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS,
5353 const IdentifierInfo *Name,
5354 ArrayRef<TemplateArgument> Args,
5355 QualType Canon);
5356
5357 const TemplateArgument *getArgBuffer() const {
5358 return reinterpret_cast<const TemplateArgument*>(this+1);
5359 }
5360
5361 TemplateArgument *getArgBuffer() {
5362 return reinterpret_cast<TemplateArgument*>(this+1);
5363 }
5364
5365public:
5366 NestedNameSpecifier *getQualifier() const { return NNS; }
5367 const IdentifierInfo *getIdentifier() const { return Name; }
5368
5369 /// Retrieve the template arguments.
5370 const TemplateArgument *getArgs() const {
5371 return getArgBuffer();
5372 }
5373
5374 /// Retrieve the number of template arguments.
5375 unsigned getNumArgs() const {
5376 return DependentTemplateSpecializationTypeBits.NumArgs;
5377 }
5378
5379 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5380
5381 ArrayRef<TemplateArgument> template_arguments() const {
5382 return {getArgs(), getNumArgs()};
5383 }
5384
5385 using iterator = const TemplateArgument *;
5386
5387 iterator begin() const { return getArgs(); }
5388 iterator end() const; // inline in TemplateBase.h
5389
5390 bool isSugared() const { return false; }
5391 QualType desugar() const { return QualType(this, 0); }
5392
5393 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5394 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5395 }
5396
5397 static void Profile(llvm::FoldingSetNodeID &ID,
5398 const ASTContext &Context,
5399 ElaboratedTypeKeyword Keyword,
5400 NestedNameSpecifier *Qualifier,
5401 const IdentifierInfo *Name,
5402 ArrayRef<TemplateArgument> Args);
5403
5404 static bool classof(const Type *T) {
5405 return T->getTypeClass() == DependentTemplateSpecialization;
5406 }
5407};
5408
5409/// Represents a pack expansion of types.
5410///
5411/// Pack expansions are part of C++11 variadic templates. A pack
5412/// expansion contains a pattern, which itself contains one or more
5413/// "unexpanded" parameter packs. When instantiated, a pack expansion
5414/// produces a series of types, each instantiated from the pattern of
5415/// the expansion, where the Ith instantiation of the pattern uses the
5416/// Ith arguments bound to each of the unexpanded parameter packs. The
5417/// pack expansion is considered to "expand" these unexpanded
5418/// parameter packs.
5419///
5420/// \code
5421/// template<typename ...Types> struct tuple;
5422///
5423/// template<typename ...Types>
5424/// struct tuple_of_references {
5425/// typedef tuple<Types&...> type;
5426/// };
5427/// \endcode
5428///
5429/// Here, the pack expansion \c Types&... is represented via a
5430/// PackExpansionType whose pattern is Types&.
5431class PackExpansionType : public Type, public llvm::FoldingSetNode {
5432 friend class ASTContext; // ASTContext creates these
5433
5434 /// The pattern of the pack expansion.
5435 QualType Pattern;
5436
5437 PackExpansionType(QualType Pattern, QualType Canon,
5438 Optional<unsigned> NumExpansions)
5439 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5440 /*InstantiationDependent=*/true,
5441 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5442 /*ContainsUnexpandedParameterPack=*/false),
5443 Pattern(Pattern) {
5444 PackExpansionTypeBits.NumExpansions =
5445 NumExpansions ? *NumExpansions + 1 : 0;
5446 }
5447
5448public:
5449 /// Retrieve the pattern of this pack expansion, which is the
5450 /// type that will be repeatedly instantiated when instantiating the
5451 /// pack expansion itself.
5452 QualType getPattern() const { return Pattern; }
5453
5454 /// Retrieve the number of expansions that this pack expansion will
5455 /// generate, if known.
5456 Optional<unsigned> getNumExpansions() const {
5457 if (PackExpansionTypeBits.NumExpansions)
5458 return PackExpansionTypeBits.NumExpansions - 1;
5459 return None;
5460 }
5461
5462 bool isSugared() const { return !Pattern->isDependentType(); }
5463 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5464
5465 void Profile(llvm::FoldingSetNodeID &ID) {
5466 Profile(ID, getPattern(), getNumExpansions());
5467 }
5468
5469 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5470 Optional<unsigned> NumExpansions) {
5471 ID.AddPointer(Pattern.getAsOpaquePtr());
5472 ID.AddBoolean(NumExpansions.hasValue());
5473 if (NumExpansions)
5474 ID.AddInteger(*NumExpansions);
5475 }
5476
5477 static bool classof(const Type *T) {
5478 return T->getTypeClass() == PackExpansion;
5479 }
5480};
5481
5482/// This class wraps the list of protocol qualifiers. For types that can
5483/// take ObjC protocol qualifers, they can subclass this class.
5484template <class T>
5485class ObjCProtocolQualifiers {
5486protected:
5487 ObjCProtocolQualifiers() = default;
5488
5489 ObjCProtocolDecl * const *getProtocolStorage() const {
5490 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5491 }
5492
5493 ObjCProtocolDecl **getProtocolStorage() {
5494 return static_cast<T*>(this)->getProtocolStorageImpl();
5495 }
5496
5497 void setNumProtocols(unsigned N) {
5498 static_cast<T*>(this)->setNumProtocolsImpl(N);
5499 }
5500
5501 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5502 setNumProtocols(protocols.size());
5503 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
5504 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
;
5505 if (!protocols.empty())
5506 memcpy(getProtocolStorage(), protocols.data(),
5507 protocols.size() * sizeof(ObjCProtocolDecl*));
5508 }
5509
5510public:
5511 using qual_iterator = ObjCProtocolDecl * const *;
5512 using qual_range = llvm::iterator_range<qual_iterator>;
5513
5514 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5515 qual_iterator qual_begin() const { return getProtocolStorage(); }
5516 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5517
5518 bool qual_empty() const { return getNumProtocols() == 0; }
5519
5520 /// Return the number of qualifying protocols in this type, or 0 if
5521 /// there are none.
5522 unsigned getNumProtocols() const {
5523 return static_cast<const T*>(this)->getNumProtocolsImpl();
5524 }
5525
5526 /// Fetch a protocol by index.
5527 ObjCProtocolDecl *getProtocol(unsigned I) const {
5528 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5528, __PRETTY_FUNCTION__))
;
5529 return qual_begin()[I];
5530 }
5531
5532 /// Retrieve all of the protocol qualifiers.
5533 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5534 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5535 }
5536};
5537
5538/// Represents a type parameter type in Objective C. It can take
5539/// a list of protocols.
5540class ObjCTypeParamType : public Type,
5541 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext;
5544 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5545
5546 /// The number of protocols stored on this type.
5547 unsigned NumProtocols : 6;
5548
5549 ObjCTypeParamDecl *OTPDecl;
5550
5551 /// The protocols are stored after the ObjCTypeParamType node. In the
5552 /// canonical type, the list of protocols are sorted alphabetically
5553 /// and uniqued.
5554 ObjCProtocolDecl **getProtocolStorageImpl();
5555
5556 /// Return the number of qualifying protocols in this interface type,
5557 /// or 0 if there are none.
5558 unsigned getNumProtocolsImpl() const {
5559 return NumProtocols;
5560 }
5561
5562 void setNumProtocolsImpl(unsigned N) {
5563 NumProtocols = N;
5564 }
5565
5566 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5567 QualType can,
5568 ArrayRef<ObjCProtocolDecl *> protocols);
5569
5570public:
5571 bool isSugared() const { return true; }
5572 QualType desugar() const { return getCanonicalTypeInternal(); }
5573
5574 static bool classof(const Type *T) {
5575 return T->getTypeClass() == ObjCTypeParam;
5576 }
5577
5578 void Profile(llvm::FoldingSetNodeID &ID);
5579 static void Profile(llvm::FoldingSetNodeID &ID,
5580 const ObjCTypeParamDecl *OTPDecl,
5581 ArrayRef<ObjCProtocolDecl *> protocols);
5582
5583 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5584};
5585
5586/// Represents a class type in Objective C.
5587///
5588/// Every Objective C type is a combination of a base type, a set of
5589/// type arguments (optional, for parameterized classes) and a list of
5590/// protocols.
5591///
5592/// Given the following declarations:
5593/// \code
5594/// \@class C<T>;
5595/// \@protocol P;
5596/// \endcode
5597///
5598/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5599/// with base C and no protocols.
5600///
5601/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5602/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5603/// protocol list.
5604/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5605/// and protocol list [P].
5606///
5607/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5608/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5609/// and no protocols.
5610///
5611/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5612/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5613/// this should get its own sugar class to better represent the source.
5614class ObjCObjectType : public Type,
5615 public ObjCProtocolQualifiers<ObjCObjectType> {
5616 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5617
5618 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5619 // after the ObjCObjectPointerType node.
5620 // ObjCObjectType.NumProtocols - the number of protocols stored
5621 // after the type arguments of ObjCObjectPointerType node.
5622 //
5623 // These protocols are those written directly on the type. If
5624 // protocol qualifiers ever become additive, the iterators will need
5625 // to get kindof complicated.
5626 //
5627 // In the canonical object type, these are sorted alphabetically
5628 // and uniqued.
5629
5630 /// Either a BuiltinType or an InterfaceType or sugar for either.
5631 QualType BaseType;
5632
5633 /// Cached superclass type.
5634 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5635 CachedSuperClassType;
5636
5637 QualType *getTypeArgStorage();
5638 const QualType *getTypeArgStorage() const {
5639 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5640 }
5641
5642 ObjCProtocolDecl **getProtocolStorageImpl();
5643 /// Return the number of qualifying protocols in this interface type,
5644 /// or 0 if there are none.
5645 unsigned getNumProtocolsImpl() const {
5646 return ObjCObjectTypeBits.NumProtocols;
5647 }
5648 void setNumProtocolsImpl(unsigned N) {
5649 ObjCObjectTypeBits.NumProtocols = N;
5650 }
5651
5652protected:
5653 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5654
5655 ObjCObjectType(QualType Canonical, QualType Base,
5656 ArrayRef<QualType> typeArgs,
5657 ArrayRef<ObjCProtocolDecl *> protocols,
5658 bool isKindOf);
5659
5660 ObjCObjectType(enum Nonce_ObjCInterface)
5661 : Type(ObjCInterface, QualType(), false, false, false, false),
5662 BaseType(QualType(this_(), 0)) {
5663 ObjCObjectTypeBits.NumProtocols = 0;
5664 ObjCObjectTypeBits.NumTypeArgs = 0;
5665 ObjCObjectTypeBits.IsKindOf = 0;
5666 }
5667
5668 void computeSuperClassTypeSlow() const;
5669
5670public:
5671 /// Gets the base type of this object type. This is always (possibly
5672 /// sugar for) one of:
5673 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5674 /// user, which is a typedef for an ObjCObjectPointerType)
5675 /// - the 'Class' builtin type (same caveat)
5676 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5677 QualType getBaseType() const { return BaseType; }
5678
5679 bool isObjCId() const {
5680 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5681 }
5682
5683 bool isObjCClass() const {
5684 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5685 }
5686
5687 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5688 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5689 bool isObjCUnqualifiedIdOrClass() const {
5690 if (!qual_empty()) return false;
5691 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5692 return T->getKind() == BuiltinType::ObjCId ||
5693 T->getKind() == BuiltinType::ObjCClass;
5694 return false;
5695 }
5696 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5697 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5698
5699 /// Gets the interface declaration for this object type, if the base type
5700 /// really is an interface.
5701 ObjCInterfaceDecl *getInterface() const;
5702
5703 /// Determine whether this object type is "specialized", meaning
5704 /// that it has type arguments.
5705 bool isSpecialized() const;
5706
5707 /// Determine whether this object type was written with type arguments.
5708 bool isSpecializedAsWritten() const {
5709 return ObjCObjectTypeBits.NumTypeArgs > 0;
5710 }
5711
5712 /// Determine whether this object type is "unspecialized", meaning
5713 /// that it has no type arguments.
5714 bool isUnspecialized() const { return !isSpecialized(); }
5715
5716 /// Determine whether this object type is "unspecialized" as
5717 /// written, meaning that it has no type arguments.
5718 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5719
5720 /// Retrieve the type arguments of this object type (semantically).
5721 ArrayRef<QualType> getTypeArgs() const;
5722
5723 /// Retrieve the type arguments of this object type as they were
5724 /// written.
5725 ArrayRef<QualType> getTypeArgsAsWritten() const {
5726 return llvm::makeArrayRef(getTypeArgStorage(),
5727 ObjCObjectTypeBits.NumTypeArgs);
5728 }
5729
5730 /// Whether this is a "__kindof" type as written.
5731 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5732
5733 /// Whether this ia a "__kindof" type (semantically).
5734 bool isKindOfType() const;
5735
5736 /// Retrieve the type of the superclass of this object type.
5737 ///
5738 /// This operation substitutes any type arguments into the
5739 /// superclass of the current class type, potentially producing a
5740 /// specialization of the superclass type. Produces a null type if
5741 /// there is no superclass.
5742 QualType getSuperClassType() const {
5743 if (!CachedSuperClassType.getInt())
5744 computeSuperClassTypeSlow();
5745
5746 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5746, __PRETTY_FUNCTION__))
;
5747 return QualType(CachedSuperClassType.getPointer(), 0);
5748 }
5749
5750 /// Strip off the Objective-C "kindof" type and (with it) any
5751 /// protocol qualifiers.
5752 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5753
5754 bool isSugared() const { return false; }
5755 QualType desugar() const { return QualType(this, 0); }
5756
5757 static bool classof(const Type *T) {
5758 return T->getTypeClass() == ObjCObject ||
5759 T->getTypeClass() == ObjCInterface;
5760 }
5761};
5762
5763/// A class providing a concrete implementation
5764/// of ObjCObjectType, so as to not increase the footprint of
5765/// ObjCInterfaceType. Code outside of ASTContext and the core type
5766/// system should not reference this type.
5767class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5768 friend class ASTContext;
5769
5770 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5771 // will need to be modified.
5772
5773 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5774 ArrayRef<QualType> typeArgs,
5775 ArrayRef<ObjCProtocolDecl *> protocols,
5776 bool isKindOf)
5777 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5778
5779public:
5780 void Profile(llvm::FoldingSetNodeID &ID);
5781 static void Profile(llvm::FoldingSetNodeID &ID,
5782 QualType Base,
5783 ArrayRef<QualType> typeArgs,
5784 ArrayRef<ObjCProtocolDecl *> protocols,
5785 bool isKindOf);
5786};
5787
5788inline QualType *ObjCObjectType::getTypeArgStorage() {
5789 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5790}
5791
5792inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5793 return reinterpret_cast<ObjCProtocolDecl**>(
5794 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5795}
5796
5797inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5798 return reinterpret_cast<ObjCProtocolDecl**>(
5799 static_cast<ObjCTypeParamType*>(this)+1);
5800}
5801
5802/// Interfaces are the core concept in Objective-C for object oriented design.
5803/// They basically correspond to C++ classes. There are two kinds of interface
5804/// types: normal interfaces like `NSString`, and qualified interfaces, which
5805/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5806///
5807/// ObjCInterfaceType guarantees the following properties when considered
5808/// as a subtype of its superclass, ObjCObjectType:
5809/// - There are no protocol qualifiers. To reinforce this, code which
5810/// tries to invoke the protocol methods via an ObjCInterfaceType will
5811/// fail to compile.
5812/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5813/// T->getBaseType() == QualType(T, 0).
5814class ObjCInterfaceType : public ObjCObjectType {
5815 friend class ASTContext; // ASTContext creates these.
5816 friend class ASTReader;
5817 friend class ObjCInterfaceDecl;
5818
5819 mutable ObjCInterfaceDecl *Decl;
5820
5821 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5822 : ObjCObjectType(Nonce_ObjCInterface),
5823 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5824
5825public:
5826 /// Get the declaration of this interface.
5827 ObjCInterfaceDecl *getDecl() const { return Decl; }
5828
5829 bool isSugared() const { return false; }
5830 QualType desugar() const { return QualType(this, 0); }
5831
5832 static bool classof(const Type *T) {
5833 return T->getTypeClass() == ObjCInterface;
5834 }
5835
5836 // Nonsense to "hide" certain members of ObjCObjectType within this
5837 // class. People asking for protocols on an ObjCInterfaceType are
5838 // not going to get what they want: ObjCInterfaceTypes are
5839 // guaranteed to have no protocols.
5840 enum {
5841 qual_iterator,
5842 qual_begin,
5843 qual_end,
5844 getNumProtocols,
5845 getProtocol
5846 };
5847};
5848
5849inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5850 QualType baseType = getBaseType();
5851 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5852 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5853 return T->getDecl();
5854
5855 baseType = ObjT->getBaseType();
5856 }
5857
5858 return nullptr;
5859}
5860
5861/// Represents a pointer to an Objective C object.
5862///
5863/// These are constructed from pointer declarators when the pointee type is
5864/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5865/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5866/// and 'Class<P>' are translated into these.
5867///
5868/// Pointers to pointers to Objective C objects are still PointerTypes;
5869/// only the first level of pointer gets it own type implementation.
5870class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5871 friend class ASTContext; // ASTContext creates these.
5872
5873 QualType PointeeType;
5874
5875 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5876 : Type(ObjCObjectPointer, Canonical,
5877 Pointee->isDependentType(),
5878 Pointee->isInstantiationDependentType(),
5879 Pointee->isVariablyModifiedType(),
5880 Pointee->containsUnexpandedParameterPack()),
5881 PointeeType(Pointee) {}
5882
5883public:
5884 /// Gets the type pointed to by this ObjC pointer.
5885 /// The result will always be an ObjCObjectType or sugar thereof.
5886 QualType getPointeeType() const { return PointeeType; }
5887
5888 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5889 ///
5890 /// This method is equivalent to getPointeeType() except that
5891 /// it discards any typedefs (or other sugar) between this
5892 /// type and the "outermost" object type. So for:
5893 /// \code
5894 /// \@class A; \@protocol P; \@protocol Q;
5895 /// typedef A<P> AP;
5896 /// typedef A A1;
5897 /// typedef A1<P> A1P;
5898 /// typedef A1P<Q> A1PQ;
5899 /// \endcode
5900 /// For 'A*', getObjectType() will return 'A'.
5901 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5902 /// For 'AP*', getObjectType() will return 'A<P>'.
5903 /// For 'A1*', getObjectType() will return 'A'.
5904 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5905 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5906 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5907 /// adding protocols to a protocol-qualified base discards the
5908 /// old qualifiers (for now). But if it didn't, getObjectType()
5909 /// would return 'A1P<Q>' (and we'd have to make iterating over
5910 /// qualifiers more complicated).
5911 const ObjCObjectType *getObjectType() const {
5912 return PointeeType->castAs<ObjCObjectType>();
5913 }
5914
5915 /// If this pointer points to an Objective C
5916 /// \@interface type, gets the type for that interface. Any protocol
5917 /// qualifiers on the interface are ignored.
5918 ///
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 const ObjCInterfaceType *getInterfaceType() const;
5921
5922 /// If this pointer points to an Objective \@interface
5923 /// type, gets the declaration for that interface.
5924 ///
5925 /// \return null if the base type for this pointer is 'id' or 'Class'
5926 ObjCInterfaceDecl *getInterfaceDecl() const {
5927 return getObjectType()->getInterface();
5928 }
5929
5930 /// True if this is equivalent to the 'id' type, i.e. if
5931 /// its object type is the primitive 'id' type with no protocols.
5932 bool isObjCIdType() const {
5933 return getObjectType()->isObjCUnqualifiedId();
5934 }
5935
5936 /// True if this is equivalent to the 'Class' type,
5937 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5938 bool isObjCClassType() const {
5939 return getObjectType()->isObjCUnqualifiedClass();
5940 }
5941
5942 /// True if this is equivalent to the 'id' or 'Class' type,
5943 bool isObjCIdOrClassType() const {
5944 return getObjectType()->isObjCUnqualifiedIdOrClass();
5945 }
5946
5947 /// True if this is equivalent to 'id<P>' for some non-empty set of
5948 /// protocols.
5949 bool isObjCQualifiedIdType() const {
5950 return getObjectType()->isObjCQualifiedId();
5951 }
5952
5953 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5954 /// protocols.
5955 bool isObjCQualifiedClassType() const {
5956 return getObjectType()->isObjCQualifiedClass();
5957 }
5958
5959 /// Whether this is a "__kindof" type.
5960 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5961
5962 /// Whether this type is specialized, meaning that it has type arguments.
5963 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5964
5965 /// Whether this type is specialized, meaning that it has type arguments.
5966 bool isSpecializedAsWritten() const {
5967 return getObjectType()->isSpecializedAsWritten();
5968 }
5969
5970 /// Whether this type is unspecialized, meaning that is has no type arguments.
5971 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5972
5973 /// Determine whether this object type is "unspecialized" as
5974 /// written, meaning that it has no type arguments.
5975 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5976
5977 /// Retrieve the type arguments for this type.
5978 ArrayRef<QualType> getTypeArgs() const {
5979 return getObjectType()->getTypeArgs();
5980 }
5981
5982 /// Retrieve the type arguments for this type.
5983 ArrayRef<QualType> getTypeArgsAsWritten() const {
5984 return getObjectType()->getTypeArgsAsWritten();
5985 }
5986
5987 /// An iterator over the qualifiers on the object type. Provided
5988 /// for convenience. This will always iterate over the full set of
5989 /// protocols on a type, not just those provided directly.
5990 using qual_iterator = ObjCObjectType::qual_iterator;
5991 using qual_range = llvm::iterator_range<qual_iterator>;
5992
5993 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5994
5995 qual_iterator qual_begin() const {
5996 return getObjectType()->qual_begin();
5997 }
5998
5999 qual_iterator qual_end() const {
6000 return getObjectType()->qual_end();
6001 }
6002
6003 bool qual_empty() const { return getObjectType()->qual_empty(); }
6004
6005 /// Return the number of qualifying protocols on the object type.
6006 unsigned getNumProtocols() const {
6007 return getObjectType()->getNumProtocols();
6008 }
6009
6010 /// Retrieve a qualifying protocol by index on the object type.
6011 ObjCProtocolDecl *getProtocol(unsigned I) const {
6012 return getObjectType()->getProtocol(I);
6013 }
6014
6015 bool isSugared() const { return false; }
6016 QualType desugar() const { return QualType(this, 0); }
6017
6018 /// Retrieve the type of the superclass of this object pointer type.
6019 ///
6020 /// This operation substitutes any type arguments into the
6021 /// superclass of the current class type, potentially producing a
6022 /// pointer to a specialization of the superclass type. Produces a
6023 /// null type if there is no superclass.
6024 QualType getSuperClassType() const;
6025
6026 /// Strip off the Objective-C "kindof" type and (with it) any
6027 /// protocol qualifiers.
6028 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6029 const ASTContext &ctx) const;
6030
6031 void Profile(llvm::FoldingSetNodeID &ID) {
6032 Profile(ID, getPointeeType());
6033 }
6034
6035 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6036 ID.AddPointer(T.getAsOpaquePtr());
6037 }
6038
6039 static bool classof(const Type *T) {
6040 return T->getTypeClass() == ObjCObjectPointer;
6041 }
6042};
6043
6044class AtomicType : public Type, public llvm::FoldingSetNode {
6045 friend class ASTContext; // ASTContext creates these.
6046
6047 QualType ValueType;
6048
6049 AtomicType(QualType ValTy, QualType Canonical)
6050 : Type(Atomic, Canonical, ValTy->isDependentType(),
6051 ValTy->isInstantiationDependentType(),
6052 ValTy->isVariablyModifiedType(),
6053 ValTy->containsUnexpandedParameterPack()),
6054 ValueType(ValTy) {}
6055
6056public:
6057 /// Gets the type contained by this atomic type, i.e.
6058 /// the type returned by performing an atomic load of this atomic type.
6059 QualType getValueType() const { return ValueType; }
6060
6061 bool isSugared() const { return false; }
6062 QualType desugar() const { return QualType(this, 0); }
6063
6064 void Profile(llvm::FoldingSetNodeID &ID) {
6065 Profile(ID, getValueType());
6066 }
6067
6068 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6069 ID.AddPointer(T.getAsOpaquePtr());
6070 }
6071
6072 static bool classof(const Type *T) {
6073 return T->getTypeClass() == Atomic;
6074 }
6075};
6076
6077/// PipeType - OpenCL20.
6078class PipeType : public Type, public llvm::FoldingSetNode {
6079 friend class ASTContext; // ASTContext creates these.
6080
6081 QualType ElementType;
6082 bool isRead;
6083
6084 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6085 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6086 elemType->isInstantiationDependentType(),
6087 elemType->isVariablyModifiedType(),
6088 elemType->containsUnexpandedParameterPack()),
6089 ElementType(elemType), isRead(isRead) {}
6090
6091public:
6092 QualType getElementType() const { return ElementType; }
6093
6094 bool isSugared() const { return false; }
6095
6096 QualType desugar() const { return QualType(this, 0); }
6097
6098 void Profile(llvm::FoldingSetNodeID &ID) {
6099 Profile(ID, getElementType(), isReadOnly());
6100 }
6101
6102 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6103 ID.AddPointer(T.getAsOpaquePtr());
6104 ID.AddBoolean(isRead);
6105 }
6106
6107 static bool classof(const Type *T) {
6108 return T->getTypeClass() == Pipe;
6109 }
6110
6111 bool isReadOnly() const { return isRead; }
6112};
6113
6114/// A qualifier set is used to build a set of qualifiers.
6115class QualifierCollector : public Qualifiers {
6116public:
6117 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6118
6119 /// Collect any qualifiers on the given type and return an
6120 /// unqualified type. The qualifiers are assumed to be consistent
6121 /// with those already in the type.
6122 const Type *strip(QualType type) {
6123 addFastQualifiers(type.getLocalFastQualifiers());
6124 if (!type.hasLocalNonFastQualifiers())
6125 return type.getTypePtrUnsafe();
6126
6127 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6128 addConsistentQualifiers(extQuals->getQualifiers());
6129 return extQuals->getBaseType();
6130 }
6131
6132 /// Apply the collected qualifiers to the given type.
6133 QualType apply(const ASTContext &Context, QualType QT) const;
6134
6135 /// Apply the collected qualifiers to the given type.
6136 QualType apply(const ASTContext &Context, const Type* T) const;
6137};
6138
6139// Inline function definitions.
6140
6141inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6142 SplitQualType desugar =
6143 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6144 desugar.Quals.addConsistentQualifiers(Quals);
6145 return desugar;
6146}
6147
6148inline const Type *QualType::getTypePtr() const {
6149 return getCommonPtr()->BaseType;
6150}
6151
6152inline const Type *QualType::getTypePtrOrNull() const {
6153 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6154}
6155
6156inline SplitQualType QualType::split() const {
6157 if (!hasLocalNonFastQualifiers())
6158 return SplitQualType(getTypePtrUnsafe(),
6159 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6160
6161 const ExtQuals *eq = getExtQualsUnsafe();
6162 Qualifiers qs = eq->getQualifiers();
6163 qs.addFastQualifiers(getLocalFastQualifiers());
6164 return SplitQualType(eq->getBaseType(), qs);
6165}
6166
6167inline Qualifiers QualType::getLocalQualifiers() const {
6168 Qualifiers Quals;
6169 if (hasLocalNonFastQualifiers())
6170 Quals = getExtQualsUnsafe()->getQualifiers();
6171 Quals.addFastQualifiers(getLocalFastQualifiers());
6172 return Quals;
6173}
6174
6175inline Qualifiers QualType::getQualifiers() const {
6176 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6177 quals.addFastQualifiers(getLocalFastQualifiers());
6178 return quals;
6179}
6180
6181inline unsigned QualType::getCVRQualifiers() const {
6182 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6183 cvr |= getLocalCVRQualifiers();
6184 return cvr;
6185}
6186
6187inline QualType QualType::getCanonicalType() const {
6188 QualType canon = getCommonPtr()->CanonicalType;
6189 return canon.withFastQualifiers(getLocalFastQualifiers());
6190}
6191
6192inline bool QualType::isCanonical() const {
6193 return getTypePtr()->isCanonicalUnqualified();
6194}
6195
6196inline bool QualType::isCanonicalAsParam() const {
6197 if (!isCanonical()) return false;
6198 if (hasLocalQualifiers()) return false;
6199
6200 const Type *T = getTypePtr();
6201 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6202 return false;
6203
6204 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6205}
6206
6207inline bool QualType::isConstQualified() const {
6208 return isLocalConstQualified() ||
6209 getCommonPtr()->CanonicalType.isLocalConstQualified();
6210}
6211
6212inline bool QualType::isRestrictQualified() const {
6213 return isLocalRestrictQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6215}
6216
6217
6218inline bool QualType::isVolatileQualified() const {
6219 return isLocalVolatileQualified() ||
6220 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6221}
6222
6223inline bool QualType::hasQualifiers() const {
6224 return hasLocalQualifiers() ||
6225 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6226}
6227
6228inline QualType QualType::getUnqualifiedType() const {
6229 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6230 return QualType(getTypePtr(), 0);
6231
6232 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6233}
6234
6235inline SplitQualType QualType::getSplitUnqualifiedType() const {
6236 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6237 return split();
6238
6239 return getSplitUnqualifiedTypeImpl(*this);
6240}
6241
6242inline void QualType::removeLocalConst() {
6243 removeLocalFastQualifiers(Qualifiers::Const);
6244}
6245
6246inline void QualType::removeLocalRestrict() {
6247 removeLocalFastQualifiers(Qualifiers::Restrict);
6248}
6249
6250inline void QualType::removeLocalVolatile() {
6251 removeLocalFastQualifiers(Qualifiers::Volatile);
6252}
6253
6254inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6255 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6255, __PRETTY_FUNCTION__))
;
6256 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6257 "Fast bits differ from CVR bits!");
6258
6259 // Fast path: we don't need to touch the slow qualifiers.
6260 removeLocalFastQualifiers(Mask);
6261}
6262
6263/// Return the address space of this type.
6264inline LangAS QualType::getAddressSpace() const {
6265 return getQualifiers().getAddressSpace();
6266}
6267
6268/// Return the gc attribute of this type.
6269inline Qualifiers::GC QualType::getObjCGCAttr() const {
6270 return getQualifiers().getObjCGCAttr();
6271}
6272
6273inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6276 return false;
6277}
6278
6279inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6282 return false;
6283}
6284
6285inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6286 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6287 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6288 return false;
6289}
6290
6291inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6292 if (const auto *PT = t.getAs<PointerType>()) {
6293 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6294 return FT->getExtInfo();
6295 } else if (const auto *FT = t.getAs<FunctionType>())
6296 return FT->getExtInfo();
6297
6298 return FunctionType::ExtInfo();
6299}
6300
6301inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6302 return getFunctionExtInfo(*t);
6303}
6304
6305/// Determine whether this type is more
6306/// qualified than the Other type. For example, "const volatile int"
6307/// is more qualified than "const int", "volatile int", and
6308/// "int". However, it is not more qualified than "const volatile
6309/// int".
6310inline bool QualType::isMoreQualifiedThan(QualType other) const {
6311 Qualifiers MyQuals = getQualifiers();
6312 Qualifiers OtherQuals = other.getQualifiers();
6313 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6314}
6315
6316/// Determine whether this type is at last
6317/// as qualified as the Other type. For example, "const volatile
6318/// int" is at least as qualified as "const int", "volatile int",
6319/// "int", and "const volatile int".
6320inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6321 Qualifiers OtherQuals = other.getQualifiers();
6322
6323 // Ignore __unaligned qualifier if this type is a void.
6324 if (getUnqualifiedType()->isVoidType())
6325 OtherQuals.removeUnaligned();
6326
6327 return getQualifiers().compatiblyIncludes(OtherQuals);
6328}
6329
6330/// If Type is a reference type (e.g., const
6331/// int&), returns the type that the reference refers to ("const
6332/// int"). Otherwise, returns the type itself. This routine is used
6333/// throughout Sema to implement C++ 5p6:
6334///
6335/// If an expression initially has the type "reference to T" (8.3.2,
6336/// 8.5.3), the type is adjusted to "T" prior to any further
6337/// analysis, the expression designates the object or function
6338/// denoted by the reference, and the expression is an lvalue.
6339inline QualType QualType::getNonReferenceType() const {
6340 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6341 return RefType->getPointeeType();
6342 else
6343 return *this;
6344}
6345
6346inline bool QualType::isCForbiddenLValueType() const {
6347 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6348 getTypePtr()->isFunctionType());
6349}
6350
6351/// Tests whether the type is categorized as a fundamental type.
6352///
6353/// \returns True for types specified in C++0x [basic.fundamental].
6354inline bool Type::isFundamentalType() const {
6355 return isVoidType() ||
6356 isNullPtrType() ||
6357 // FIXME: It's really annoying that we don't have an
6358 // 'isArithmeticType()' which agrees with the standard definition.
6359 (isArithmeticType() && !isEnumeralType());
6360}
6361
6362/// Tests whether the type is categorized as a compound type.
6363///
6364/// \returns True for types specified in C++0x [basic.compound].
6365inline bool Type::isCompoundType() const {
6366 // C++0x [basic.compound]p1:
6367 // Compound types can be constructed in the following ways:
6368 // -- arrays of objects of a given type [...];
6369 return isArrayType() ||
6370 // -- functions, which have parameters of given types [...];
6371 isFunctionType() ||
6372 // -- pointers to void or objects or functions [...];
6373 isPointerType() ||
6374 // -- references to objects or functions of a given type. [...]
6375 isReferenceType() ||
6376 // -- classes containing a sequence of objects of various types, [...];
6377 isRecordType() ||
6378 // -- unions, which are classes capable of containing objects of different
6379 // types at different times;
6380 isUnionType() ||
6381 // -- enumerations, which comprise a set of named constant values. [...];
6382 isEnumeralType() ||
6383 // -- pointers to non-static class members, [...].
6384 isMemberPointerType();
6385}
6386
6387inline bool Type::isFunctionType() const {
6388 return isa<FunctionType>(CanonicalType);
6389}
6390
6391inline bool Type::isPointerType() const {
6392 return isa<PointerType>(CanonicalType);
6393}
6394
6395inline bool Type::isAnyPointerType() const {
6396 return isPointerType() || isObjCObjectPointerType();
6397}
6398
6399inline bool Type::isBlockPointerType() const {
6400 return isa<BlockPointerType>(CanonicalType);
6401}
6402
6403inline bool Type::isReferenceType() const {
6404 return isa<ReferenceType>(CanonicalType);
6405}
6406
6407inline bool Type::isLValueReferenceType() const {
6408 return isa<LValueReferenceType>(CanonicalType);
6409}
6410
6411inline bool Type::isRValueReferenceType() const {
6412 return isa<RValueReferenceType>(CanonicalType);
6413}
6414
6415inline bool Type::isFunctionPointerType() const {
6416 if (const auto *T = getAs<PointerType>())
6417 return T->getPointeeType()->isFunctionType();
6418 else
6419 return false;
6420}
6421
6422inline bool Type::isFunctionReferenceType() const {
6423 if (const auto *T = getAs<ReferenceType>())
6424 return T->getPointeeType()->isFunctionType();
6425 else
6426 return false;
6427}
6428
6429inline bool Type::isMemberPointerType() const {
6430 return isa<MemberPointerType>(CanonicalType);
6431}
6432
6433inline bool Type::isMemberFunctionPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberFunctionPointer();
6436 else
6437 return false;
6438}
6439
6440inline bool Type::isMemberDataPointerType() const {
6441 if (const auto *T = getAs<MemberPointerType>())
6442 return T->isMemberDataPointer();
6443 else
6444 return false;
6445}
6446
6447inline bool Type::isArrayType() const {
6448 return isa<ArrayType>(CanonicalType);
6449}
6450
6451inline bool Type::isConstantArrayType() const {
6452 return isa<ConstantArrayType>(CanonicalType);
6453}
6454
6455inline bool Type::isIncompleteArrayType() const {
6456 return isa<IncompleteArrayType>(CanonicalType);
6457}
6458
6459inline bool Type::isVariableArrayType() const {
6460 return isa<VariableArrayType>(CanonicalType);
6461}
6462
6463inline bool Type::isDependentSizedArrayType() const {
6464 return isa<DependentSizedArrayType>(CanonicalType);
6465}
6466
6467inline bool Type::isBuiltinType() const {
6468 return isa<BuiltinType>(CanonicalType);
6469}
6470
6471inline bool Type::isRecordType() const {
6472 return isa<RecordType>(CanonicalType);
17
Assuming field 'CanonicalType' is a 'RecordType'
18
Returning the value 1, which participates in a condition later
6473}
6474
6475inline bool Type::isEnumeralType() const {
6476 return isa<EnumType>(CanonicalType);
6477}
6478
6479inline bool Type::isAnyComplexType() const {
6480 return isa<ComplexType>(CanonicalType);
6481}
6482
6483inline bool Type::isVectorType() const {
6484 return isa<VectorType>(CanonicalType);
6485}
6486
6487inline bool Type::isExtVectorType() const {
6488 return isa<ExtVectorType>(CanonicalType);
6489}
6490
6491inline bool Type::isDependentAddressSpaceType() const {
6492 return isa<DependentAddressSpaceType>(CanonicalType);
6493}
6494
6495inline bool Type::isObjCObjectPointerType() const {
6496 return isa<ObjCObjectPointerType>(CanonicalType);
6497}
6498
6499inline bool Type::isObjCObjectType() const {
6500 return isa<ObjCObjectType>(CanonicalType);
6501}
6502
6503inline bool Type::isObjCObjectOrInterfaceType() const {
6504 return isa<ObjCInterfaceType>(CanonicalType) ||
6505 isa<ObjCObjectType>(CanonicalType);
6506}
6507
6508inline bool Type::isAtomicType() const {
6509 return isa<AtomicType>(CanonicalType);
6510}
6511
6512inline bool Type::isObjCQualifiedIdType() const {
6513 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6514 return OPT->isObjCQualifiedIdType();
6515 return false;
6516}
6517
6518inline bool Type::isObjCQualifiedClassType() const {
6519 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6520 return OPT->isObjCQualifiedClassType();
6521 return false;
6522}
6523
6524inline bool Type::isObjCIdType() const {
6525 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6526 return OPT->isObjCIdType();
6527 return false;
6528}
6529
6530inline bool Type::isObjCClassType() const {
6531 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6532 return OPT->isObjCClassType();
6533 return false;
6534}
6535
6536inline bool Type::isObjCSelType() const {
6537 if (const auto *OPT = getAs<PointerType>())
6538 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6539 return false;
6540}
6541
6542inline bool Type::isObjCBuiltinType() const {
6543 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6544}
6545
6546inline bool Type::isDecltypeType() const {
6547 return isa<DecltypeType>(this);
6548}
6549
6550#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6551 inline bool Type::is##Id##Type() const { \
6552 return isSpecificBuiltinType(BuiltinType::Id); \
6553 }
6554#include "clang/Basic/OpenCLImageTypes.def"
6555
6556inline bool Type::isSamplerT() const {
6557 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6558}
6559
6560inline bool Type::isEventT() const {
6561 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6562}
6563
6564inline bool Type::isClkEventT() const {
6565 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6566}
6567
6568inline bool Type::isQueueT() const {
6569 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6570}
6571
6572inline bool Type::isReserveIDT() const {
6573 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6574}
6575
6576inline bool Type::isImageType() const {
6577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6578 return
6579#include "clang/Basic/OpenCLImageTypes.def"
6580 false; // end boolean or operation
6581}
6582
6583inline bool Type::isPipeType() const {
6584 return isa<PipeType>(CanonicalType);
6585}
6586
6587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6588 inline bool Type::is##Id##Type() const { \
6589 return isSpecificBuiltinType(BuiltinType::Id); \
6590 }
6591#include "clang/Basic/OpenCLExtensionTypes.def"
6592
6593inline bool Type::isOCLIntelSubgroupAVCType() const {
6594#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6595 isOCLIntelSubgroupAVC##Id##Type() ||
6596 return
6597#include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6599}
6600
6601inline bool Type::isOCLExtOpaqueType() const {
6602#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6603 return
6604#include "clang/Basic/OpenCLExtensionTypes.def"
6605 false; // end of boolean or operation
6606}
6607
6608inline bool Type::isOpenCLSpecificType() const {
6609 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6610 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6611}
6612
6613inline bool Type::isTemplateTypeParmType() const {
6614 return isa<TemplateTypeParmType>(CanonicalType);
6615}
6616
6617inline bool Type::isSpecificBuiltinType(unsigned K) const {
6618 if (const BuiltinType *BT = getAs<BuiltinType>())
6619 if (BT->getKind() == (BuiltinType::Kind) K)
6620 return true;
6621 return false;
6622}
6623
6624inline bool Type::isPlaceholderType() const {
6625 if (const auto *BT = dyn_cast<BuiltinType>(this))
6626 return BT->isPlaceholderType();
6627 return false;
6628}
6629
6630inline const BuiltinType *Type::getAsPlaceholderType() const {
6631 if (const auto *BT = dyn_cast<BuiltinType>(this))
6632 if (BT->isPlaceholderType())
6633 return BT;
6634 return nullptr;
6635}
6636
6637inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6638 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6638, __PRETTY_FUNCTION__))
;
6639 if (const auto *BT = dyn_cast<BuiltinType>(this))
6640 return (BT->getKind() == (BuiltinType::Kind) K);
6641 return false;
6642}
6643
6644inline bool Type::isNonOverloadPlaceholderType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(this))
6646 return BT->isNonOverloadPlaceholderType();
6647 return false;
6648}
6649
6650inline bool Type::isVoidType() const {
6651 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6652 return BT->getKind() == BuiltinType::Void;
6653 return false;
6654}
6655
6656inline bool Type::isHalfType() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Half;
6659 // FIXME: Should we allow complex __fp16? Probably not.
6660 return false;
6661}
6662
6663inline bool Type::isFloat16Type() const {
6664 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6665 return BT->getKind() == BuiltinType::Float16;
6666 return false;
6667}
6668
6669inline bool Type::isFloat128Type() const {
6670 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6671 return BT->getKind() == BuiltinType::Float128;
6672 return false;
6673}
6674
6675inline bool Type::isNullPtrType() const {
6676 if (const auto *BT = getAs<BuiltinType>())
6677 return BT->getKind() == BuiltinType::NullPtr;
6678 return false;
6679}
6680
6681bool IsEnumDeclComplete(EnumDecl *);
6682bool IsEnumDeclScoped(EnumDecl *);
6683
6684inline bool Type::isIntegerType() const {
6685 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6686 return BT->getKind() >= BuiltinType::Bool &&
6687 BT->getKind() <= BuiltinType::Int128;
6688 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6689 // Incomplete enum types are not treated as integer types.
6690 // FIXME: In C++, enum types are never integer types.
6691 return IsEnumDeclComplete(ET->getDecl()) &&
6692 !IsEnumDeclScoped(ET->getDecl());
6693 }
6694 return false;
6695}
6696
6697inline bool Type::isFixedPointType() const {
6698 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6699 return BT->getKind() >= BuiltinType::ShortAccum &&
6700 BT->getKind() <= BuiltinType::SatULongFract;
6701 }
6702 return false;
6703}
6704
6705inline bool Type::isFixedPointOrIntegerType() const {
6706 return isFixedPointType() || isIntegerType();
6707}
6708
6709inline bool Type::isSaturatedFixedPointType() const {
6710 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6711 return BT->getKind() >= BuiltinType::SatShortAccum &&
6712 BT->getKind() <= BuiltinType::SatULongFract;
6713 }
6714 return false;
6715}
6716
6717inline bool Type::isUnsaturatedFixedPointType() const {
6718 return isFixedPointType() && !isSaturatedFixedPointType();
6719}
6720
6721inline bool Type::isSignedFixedPointType() const {
6722 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6723 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6724 BT->getKind() <= BuiltinType::LongAccum) ||
6725 (BT->getKind() >= BuiltinType::ShortFract &&
6726 BT->getKind() <= BuiltinType::LongFract) ||
6727 (BT->getKind() >= BuiltinType::SatShortAccum &&
6728 BT->getKind() <= BuiltinType::SatLongAccum) ||
6729 (BT->getKind() >= BuiltinType::SatShortFract &&
6730 BT->getKind() <= BuiltinType::SatLongFract));
6731 }
6732 return false;
6733}
6734
6735inline bool Type::isUnsignedFixedPointType() const {
6736 return isFixedPointType() && !isSignedFixedPointType();
6737}
6738
6739inline bool Type::isScalarType() const {
6740 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6741 return BT->getKind() > BuiltinType::Void &&
6742 BT->getKind() <= BuiltinType::NullPtr;
6743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6744 // Enums are scalar types, but only if they are defined. Incomplete enums
6745 // are not treated as scalar types.
6746 return IsEnumDeclComplete(ET->getDecl());
6747 return isa<PointerType>(CanonicalType) ||
6748 isa<BlockPointerType>(CanonicalType) ||
6749 isa<MemberPointerType>(CanonicalType) ||
6750 isa<ComplexType>(CanonicalType) ||
6751 isa<ObjCObjectPointerType>(CanonicalType);
6752}
6753
6754inline bool Type::isIntegralOrEnumerationType() const {
6755 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6756 return BT->getKind() >= BuiltinType::Bool &&
6757 BT->getKind() <= BuiltinType::Int128;
6758
6759 // Check for a complete enum type; incomplete enum types are not properly an
6760 // enumeration type in the sense required here.
6761 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6762 return IsEnumDeclComplete(ET->getDecl());
6763
6764 return false;
6765}
6766
6767inline bool Type::isBooleanType() const {
6768 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6769 return BT->getKind() == BuiltinType::Bool;
6770 return false;
6771}
6772
6773inline bool Type::isUndeducedType() const {
6774 auto *DT = getContainedDeducedType();
6775 return DT && !DT->isDeduced();
6776}
6777
6778/// Determines whether this is a type for which one can define
6779/// an overloaded operator.
6780inline bool Type::isOverloadableType() const {
6781 return isDependentType() || isRecordType() || isEnumeralType();
6782}
6783
6784/// Determines whether this type can decay to a pointer type.
6785inline bool Type::canDecayToPointerType() const {
6786 return isFunctionType() || isArrayType();
6787}
6788
6789inline bool Type::hasPointerRepresentation() const {
6790 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6791 isObjCObjectPointerType() || isNullPtrType());
6792}
6793
6794inline bool Type::hasObjCPointerRepresentation() const {
6795 return isObjCObjectPointerType();
6796}
6797
6798inline const Type *Type::getBaseElementTypeUnsafe() const {
6799 const Type *type = this;
6800 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6801 type = arrayType->getElementType().getTypePtr();
6802 return type;
6803}
6804
6805inline const Type *Type::getPointeeOrArrayElementType() const {
6806 const Type *type = this;
6807 if (type->isAnyPointerType())
6808 return type->getPointeeType().getTypePtr();
6809 else if (type->isArrayType())
6810 return type->getBaseElementTypeUnsafe();
6811 return type;
6812}
6813
6814/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6815/// diagnostic with <<.
6816inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6817 Qualifiers Q) {
6818 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6819 DiagnosticsEngine::ArgumentKind::ak_qual);
6820 return DB;
6821}
6822
6823/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6824/// into a diagnostic with <<.
6825inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6826 Qualifiers Q) {
6827 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6828 DiagnosticsEngine::ArgumentKind::ak_qual);
6829 return PD;
6830}
6831
6832/// Insertion operator for diagnostics. This allows sending QualType's into a
6833/// diagnostic with <<.
6834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6835 QualType T) {
6836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6837 DiagnosticsEngine::ak_qualtype);
6838 return DB;
6839}
6840
6841/// Insertion operator for partial diagnostics. This allows sending QualType's
6842/// into a diagnostic with <<.
6843inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6844 QualType T) {
6845 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6846 DiagnosticsEngine::ak_qualtype);
6847 return PD;
6848}
6849
6850// Helper class template that is used by Type::getAs to ensure that one does
6851// not try to look through a qualified type to get to an array type.
6852template <typename T>
6853using TypeIsArrayType =
6854 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6855 std::is_base_of<ArrayType, T>::value>;
6856
6857// Member-template getAs<specific type>'.
6858template <typename T> const T *Type::getAs() const {
6859 static_assert(!TypeIsArrayType<T>::value,
6860 "ArrayType cannot be used with getAs!");
6861
6862 // If this is directly a T type, return it.
6863 if (const auto *Ty = dyn_cast<T>(this))
6864 return Ty;
6865
6866 // If the canonical form of this type isn't the right kind, reject it.
6867 if (!isa<T>(CanonicalType))
6868 return nullptr;
6869
6870 // If this is a typedef for the type, strip the typedef off without
6871 // losing all typedef information.
6872 return cast<T>(getUnqualifiedDesugaredType());
6873}
6874
6875template <typename T> const T *Type::getAsAdjusted() const {
6876 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6877
6878 // If this is directly a T type, return it.
6879 if (const auto *Ty = dyn_cast<T>(this))
6880 return Ty;
6881
6882 // If the canonical form of this type isn't the right kind, reject it.
6883 if (!isa<T>(CanonicalType))
6884 return nullptr;
6885
6886 // Strip off type adjustments that do not modify the underlying nature of the
6887 // type.
6888 const Type *Ty = this;
6889 while (Ty) {
6890 if (const auto *A = dyn_cast<AttributedType>(Ty))
6891 Ty = A->getModifiedType().getTypePtr();
6892 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6893 Ty = E->desugar().getTypePtr();
6894 else if (const auto *P = dyn_cast<ParenType>(Ty))
6895 Ty = P->desugar().getTypePtr();
6896 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6897 Ty = A->desugar().getTypePtr();
6898 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6899 Ty = M->desugar().getTypePtr();
6900 else
6901 break;
6902 }
6903
6904 // Just because the canonical type is correct does not mean we can use cast<>,
6905 // since we may not have stripped off all the sugar down to the base type.
6906 return dyn_cast<T>(Ty);
6907}
6908
6909inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6910 // If this is directly an array type, return it.
6911 if (const auto *arr = dyn_cast<ArrayType>(this))
6912 return arr;
6913
6914 // If the canonical form of this type isn't the right kind, reject it.
6915 if (!isa<ArrayType>(CanonicalType))
6916 return nullptr;
6917
6918 // If this is a typedef for the type, strip the typedef off without
6919 // losing all typedef information.
6920 return cast<ArrayType>(getUnqualifiedDesugaredType());
6921}
6922
6923template <typename T> const T *Type::castAs() const {
6924 static_assert(!TypeIsArrayType<T>::value,
6925 "ArrayType cannot be used with castAs!");
6926
6927 if (const auto *ty = dyn_cast<T>(this)) return ty;
6928 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6928, __PRETTY_FUNCTION__))
;
6929 return cast<T>(getUnqualifiedDesugaredType());
6930}
6931
6932inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6933 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6933, __PRETTY_FUNCTION__))
;
6934 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6935 return cast<ArrayType>(getUnqualifiedDesugaredType());
6936}
6937
6938DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6939 QualType CanonicalPtr)
6940 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6941#ifndef NDEBUG
6942 QualType Adjusted = getAdjustedType();
6943 (void)AttributedType::stripOuterNullability(Adjusted);
6944 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6944, __PRETTY_FUNCTION__))
;
6945#endif
6946}
6947
6948QualType DecayedType::getPointeeType() const {
6949 QualType Decayed = getDecayedType();
6950 (void)AttributedType::stripOuterNullability(Decayed);
6951 return cast<PointerType>(Decayed)->getPointeeType();
6952}
6953
6954// Get the decimal string representation of a fixed point type, represented
6955// as a scaled integer.
6956// TODO: At some point, we should change the arguments to instead just accept an
6957// APFixedPoint instead of APSInt and scale.
6958void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6959 unsigned Scale);
6960
6961} // namespace clang
6962
6963#endif // LLVM_CLANG_AST_TYPE_H