File: | tools/clang/include/clang/Sema/Sema.h |
Warning: | line 826, column 7 Passed-by-value struct argument contains uninitialized data (e.g., field: 'SavedInNonInstantiationSFINAEContext') |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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/PartialDiagnostic.h" | |||
28 | #include "clang/Basic/TargetInfo.h" | |||
29 | #include "clang/Lex/LiteralSupport.h" | |||
30 | #include "clang/Lex/Preprocessor.h" | |||
31 | #include "clang/Sema/CXXFieldCollector.h" | |||
32 | #include "clang/Sema/DeclSpec.h" | |||
33 | #include "clang/Sema/Initialization.h" | |||
34 | #include "clang/Sema/Lookup.h" | |||
35 | #include "clang/Sema/ParsedTemplate.h" | |||
36 | #include "clang/Sema/Scope.h" | |||
37 | #include "clang/Sema/ScopeInfo.h" | |||
38 | #include "clang/Sema/SemaInternal.h" | |||
39 | #include "clang/Sema/Template.h" | |||
40 | #include "llvm/ADT/STLExtras.h" | |||
41 | #include "llvm/ADT/SmallString.h" | |||
42 | #include "llvm/ADT/StringExtras.h" | |||
43 | #include <map> | |||
44 | #include <set> | |||
45 | ||||
46 | using namespace clang; | |||
47 | ||||
48 | //===----------------------------------------------------------------------===// | |||
49 | // CheckDefaultArgumentVisitor | |||
50 | //===----------------------------------------------------------------------===// | |||
51 | ||||
52 | namespace { | |||
53 | /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses | |||
54 | /// the default argument of a parameter to determine whether it | |||
55 | /// contains any ill-formed subexpressions. For example, this will | |||
56 | /// diagnose the use of local variables or parameters within the | |||
57 | /// default argument expression. | |||
58 | class CheckDefaultArgumentVisitor | |||
59 | : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { | |||
60 | Expr *DefaultArg; | |||
61 | Sema *S; | |||
62 | ||||
63 | public: | |||
64 | CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) | |||
65 | : DefaultArg(defarg), S(s) {} | |||
66 | ||||
67 | bool VisitExpr(Expr *Node); | |||
68 | bool VisitDeclRefExpr(DeclRefExpr *DRE); | |||
69 | bool VisitCXXThisExpr(CXXThisExpr *ThisE); | |||
70 | bool VisitLambdaExpr(LambdaExpr *Lambda); | |||
71 | bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); | |||
72 | }; | |||
73 | ||||
74 | /// VisitExpr - Visit all of the children of this expression. | |||
75 | bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { | |||
76 | bool IsInvalid = false; | |||
77 | for (Stmt *SubStmt : Node->children()) | |||
78 | IsInvalid |= Visit(SubStmt); | |||
79 | return IsInvalid; | |||
80 | } | |||
81 | ||||
82 | /// VisitDeclRefExpr - Visit a reference to a declaration, to | |||
83 | /// determine whether this declaration can be used in the default | |||
84 | /// argument expression. | |||
85 | bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { | |||
86 | NamedDecl *Decl = DRE->getDecl(); | |||
87 | if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { | |||
88 | // C++ [dcl.fct.default]p9 | |||
89 | // Default arguments are evaluated each time the function is | |||
90 | // called. The order of evaluation of function arguments is | |||
91 | // unspecified. Consequently, parameters of a function shall not | |||
92 | // be used in default argument expressions, even if they are not | |||
93 | // evaluated. Parameters of a function declared before a default | |||
94 | // argument expression are in scope and can hide namespace and | |||
95 | // class member names. | |||
96 | return S->Diag(DRE->getBeginLoc(), | |||
97 | diag::err_param_default_argument_references_param) | |||
98 | << Param->getDeclName() << DefaultArg->getSourceRange(); | |||
99 | } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { | |||
100 | // C++ [dcl.fct.default]p7 | |||
101 | // Local variables shall not be used in default argument | |||
102 | // expressions. | |||
103 | if (VDecl->isLocalVarDecl()) | |||
104 | return S->Diag(DRE->getBeginLoc(), | |||
105 | diag::err_param_default_argument_references_local) | |||
106 | << VDecl->getDeclName() << DefaultArg->getSourceRange(); | |||
107 | } | |||
108 | ||||
109 | return false; | |||
110 | } | |||
111 | ||||
112 | /// VisitCXXThisExpr - Visit a C++ "this" expression. | |||
113 | bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { | |||
114 | // C++ [dcl.fct.default]p8: | |||
115 | // The keyword this shall not be used in a default argument of a | |||
116 | // member function. | |||
117 | return S->Diag(ThisE->getBeginLoc(), | |||
118 | diag::err_param_default_argument_references_this) | |||
119 | << ThisE->getSourceRange(); | |||
120 | } | |||
121 | ||||
122 | bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { | |||
123 | bool Invalid = false; | |||
124 | for (PseudoObjectExpr::semantics_iterator | |||
125 | i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { | |||
126 | Expr *E = *i; | |||
127 | ||||
128 | // Look through bindings. | |||
129 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | |||
130 | E = OVE->getSourceExpr(); | |||
131 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 131, __PRETTY_FUNCTION__)); | |||
132 | } | |||
133 | ||||
134 | Invalid |= Visit(E); | |||
135 | } | |||
136 | return Invalid; | |||
137 | } | |||
138 | ||||
139 | bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { | |||
140 | // C++11 [expr.lambda.prim]p13: | |||
141 | // A lambda-expression appearing in a default argument shall not | |||
142 | // implicitly or explicitly capture any entity. | |||
143 | if (Lambda->capture_begin() == Lambda->capture_end()) | |||
144 | return false; | |||
145 | ||||
146 | return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); | |||
147 | } | |||
148 | } | |||
149 | ||||
150 | void | |||
151 | Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, | |||
152 | const CXXMethodDecl *Method) { | |||
153 | // If we have an MSAny spec already, don't bother. | |||
154 | if (!Method || ComputedEST == EST_MSAny) | |||
155 | return; | |||
156 | ||||
157 | const FunctionProtoType *Proto | |||
158 | = Method->getType()->getAs<FunctionProtoType>(); | |||
159 | Proto = Self->ResolveExceptionSpec(CallLoc, Proto); | |||
160 | if (!Proto) | |||
161 | return; | |||
162 | ||||
163 | ExceptionSpecificationType EST = Proto->getExceptionSpecType(); | |||
164 | ||||
165 | // If we have a throw-all spec at this point, ignore the function. | |||
166 | if (ComputedEST == EST_None) | |||
167 | return; | |||
168 | ||||
169 | if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) | |||
170 | EST = EST_BasicNoexcept; | |||
171 | ||||
172 | switch (EST) { | |||
173 | case EST_Unparsed: | |||
174 | case EST_Uninstantiated: | |||
175 | case EST_Unevaluated: | |||
176 | llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 176); | |||
177 | ||||
178 | // If this function can throw any exceptions, make a note of that. | |||
179 | case EST_MSAny: | |||
180 | case EST_None: | |||
181 | // FIXME: Whichever we see last of MSAny and None determines our result. | |||
182 | // We should make a consistent, order-independent choice here. | |||
183 | ClearExceptions(); | |||
184 | ComputedEST = EST; | |||
185 | return; | |||
186 | case EST_NoexceptFalse: | |||
187 | ClearExceptions(); | |||
188 | ComputedEST = EST_None; | |||
189 | return; | |||
190 | // FIXME: If the call to this decl is using any of its default arguments, we | |||
191 | // need to search them for potentially-throwing calls. | |||
192 | // If this function has a basic noexcept, it doesn't affect the outcome. | |||
193 | case EST_BasicNoexcept: | |||
194 | case EST_NoexceptTrue: | |||
195 | return; | |||
196 | // If we're still at noexcept(true) and there's a throw() callee, | |||
197 | // change to that specification. | |||
198 | case EST_DynamicNone: | |||
199 | if (ComputedEST == EST_BasicNoexcept) | |||
200 | ComputedEST = EST_DynamicNone; | |||
201 | return; | |||
202 | case EST_DependentNoexcept: | |||
203 | llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 204) | |||
204 | "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 204); | |||
205 | case EST_Dynamic: | |||
206 | break; | |||
207 | } | |||
208 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 208, __PRETTY_FUNCTION__)); | |||
209 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 210, __PRETTY_FUNCTION__)) | |||
210 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 210, __PRETTY_FUNCTION__)); | |||
211 | ComputedEST = EST_Dynamic; | |||
212 | // Record the exceptions in this function's exception specification. | |||
213 | for (const auto &E : Proto->exceptions()) | |||
214 | if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) | |||
215 | Exceptions.push_back(E); | |||
216 | } | |||
217 | ||||
218 | void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { | |||
219 | if (!E || ComputedEST == EST_MSAny) | |||
220 | return; | |||
221 | ||||
222 | // FIXME: | |||
223 | // | |||
224 | // C++0x [except.spec]p14: | |||
225 | // [An] implicit exception-specification specifies the type-id T if and | |||
226 | // only if T is allowed by the exception-specification of a function directly | |||
227 | // invoked by f's implicit definition; f shall allow all exceptions if any | |||
228 | // function it directly invokes allows all exceptions, and f shall allow no | |||
229 | // exceptions if every function it directly invokes allows no exceptions. | |||
230 | // | |||
231 | // Note in particular that if an implicit exception-specification is generated | |||
232 | // for a function containing a throw-expression, that specification can still | |||
233 | // be noexcept(true). | |||
234 | // | |||
235 | // Note also that 'directly invoked' is not defined in the standard, and there | |||
236 | // is no indication that we should only consider potentially-evaluated calls. | |||
237 | // | |||
238 | // Ultimately we should implement the intent of the standard: the exception | |||
239 | // specification should be the set of exceptions which can be thrown by the | |||
240 | // implicit definition. For now, we assume that any non-nothrow expression can | |||
241 | // throw any exception. | |||
242 | ||||
243 | if (Self->canThrow(E)) | |||
244 | ComputedEST = EST_None; | |||
245 | } | |||
246 | ||||
247 | bool | |||
248 | Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, | |||
249 | SourceLocation EqualLoc) { | |||
250 | if (RequireCompleteType(Param->getLocation(), Param->getType(), | |||
251 | diag::err_typecheck_decl_incomplete_type)) { | |||
252 | Param->setInvalidDecl(); | |||
253 | return true; | |||
254 | } | |||
255 | ||||
256 | // C++ [dcl.fct.default]p5 | |||
257 | // A default argument expression is implicitly converted (clause | |||
258 | // 4) to the parameter type. The default argument expression has | |||
259 | // the same semantic constraints as the initializer expression in | |||
260 | // a declaration of a variable of the parameter type, using the | |||
261 | // copy-initialization semantics (8.5). | |||
262 | InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, | |||
263 | Param); | |||
264 | InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), | |||
265 | EqualLoc); | |||
266 | InitializationSequence InitSeq(*this, Entity, Kind, Arg); | |||
267 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); | |||
268 | if (Result.isInvalid()) | |||
269 | return true; | |||
270 | Arg = Result.getAs<Expr>(); | |||
271 | ||||
272 | CheckCompletedExpr(Arg, EqualLoc); | |||
273 | Arg = MaybeCreateExprWithCleanups(Arg); | |||
274 | ||||
275 | // Okay: add the default argument to the parameter | |||
276 | Param->setDefaultArg(Arg); | |||
277 | ||||
278 | // We have already instantiated this parameter; provide each of the | |||
279 | // instantiations with the uninstantiated default argument. | |||
280 | UnparsedDefaultArgInstantiationsMap::iterator InstPos | |||
281 | = UnparsedDefaultArgInstantiations.find(Param); | |||
282 | if (InstPos != UnparsedDefaultArgInstantiations.end()) { | |||
283 | for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) | |||
284 | InstPos->second[I]->setUninstantiatedDefaultArg(Arg); | |||
285 | ||||
286 | // We're done tracking this parameter's instantiations. | |||
287 | UnparsedDefaultArgInstantiations.erase(InstPos); | |||
288 | } | |||
289 | ||||
290 | return false; | |||
291 | } | |||
292 | ||||
293 | /// ActOnParamDefaultArgument - Check whether the default argument | |||
294 | /// provided for a function parameter is well-formed. If so, attach it | |||
295 | /// to the parameter declaration. | |||
296 | void | |||
297 | Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, | |||
298 | Expr *DefaultArg) { | |||
299 | if (!param || !DefaultArg) | |||
300 | return; | |||
301 | ||||
302 | ParmVarDecl *Param = cast<ParmVarDecl>(param); | |||
303 | UnparsedDefaultArgLocs.erase(Param); | |||
304 | ||||
305 | // Default arguments are only permitted in C++ | |||
306 | if (!getLangOpts().CPlusPlus) { | |||
307 | Diag(EqualLoc, diag::err_param_default_argument) | |||
308 | << DefaultArg->getSourceRange(); | |||
309 | Param->setInvalidDecl(); | |||
310 | return; | |||
311 | } | |||
312 | ||||
313 | // Check for unexpanded parameter packs. | |||
314 | if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { | |||
315 | Param->setInvalidDecl(); | |||
316 | return; | |||
317 | } | |||
318 | ||||
319 | // C++11 [dcl.fct.default]p3 | |||
320 | // A default argument expression [...] shall not be specified for a | |||
321 | // parameter pack. | |||
322 | if (Param->isParameterPack()) { | |||
323 | Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) | |||
324 | << DefaultArg->getSourceRange(); | |||
325 | return; | |||
326 | } | |||
327 | ||||
328 | // Check that the default argument is well-formed | |||
329 | CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); | |||
330 | if (DefaultArgChecker.Visit(DefaultArg)) { | |||
331 | Param->setInvalidDecl(); | |||
332 | return; | |||
333 | } | |||
334 | ||||
335 | SetParamDefaultArgument(Param, DefaultArg, EqualLoc); | |||
336 | } | |||
337 | ||||
338 | /// ActOnParamUnparsedDefaultArgument - We've seen a default | |||
339 | /// argument for a function parameter, but we can't parse it yet | |||
340 | /// because we're inside a class definition. Note that this default | |||
341 | /// argument will be parsed later. | |||
342 | void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, | |||
343 | SourceLocation EqualLoc, | |||
344 | SourceLocation ArgLoc) { | |||
345 | if (!param) | |||
346 | return; | |||
347 | ||||
348 | ParmVarDecl *Param = cast<ParmVarDecl>(param); | |||
349 | Param->setUnparsedDefaultArg(); | |||
350 | UnparsedDefaultArgLocs[Param] = ArgLoc; | |||
351 | } | |||
352 | ||||
353 | /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of | |||
354 | /// the default argument for the parameter param failed. | |||
355 | void Sema::ActOnParamDefaultArgumentError(Decl *param, | |||
356 | SourceLocation EqualLoc) { | |||
357 | if (!param) | |||
358 | return; | |||
359 | ||||
360 | ParmVarDecl *Param = cast<ParmVarDecl>(param); | |||
361 | Param->setInvalidDecl(); | |||
362 | UnparsedDefaultArgLocs.erase(Param); | |||
363 | Param->setDefaultArg(new(Context) | |||
364 | OpaqueValueExpr(EqualLoc, | |||
365 | Param->getType().getNonReferenceType(), | |||
366 | VK_RValue)); | |||
367 | } | |||
368 | ||||
369 | /// CheckExtraCXXDefaultArguments - Check for any extra default | |||
370 | /// arguments in the declarator, which is not a function declaration | |||
371 | /// or definition and therefore is not permitted to have default | |||
372 | /// arguments. This routine should be invoked for every declarator | |||
373 | /// that is not a function declaration or definition. | |||
374 | void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { | |||
375 | // C++ [dcl.fct.default]p3 | |||
376 | // A default argument expression shall be specified only in the | |||
377 | // parameter-declaration-clause of a function declaration or in a | |||
378 | // template-parameter (14.1). It shall not be specified for a | |||
379 | // parameter pack. If it is specified in a | |||
380 | // parameter-declaration-clause, it shall not occur within a | |||
381 | // declarator or abstract-declarator of a parameter-declaration. | |||
382 | bool MightBeFunction = D.isFunctionDeclarationContext(); | |||
383 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
384 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
385 | if (chunk.Kind == DeclaratorChunk::Function) { | |||
386 | if (MightBeFunction) { | |||
387 | // This is a function declaration. It can have default arguments, but | |||
388 | // keep looking in case its return type is a function type with default | |||
389 | // arguments. | |||
390 | MightBeFunction = false; | |||
391 | continue; | |||
392 | } | |||
393 | for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; | |||
394 | ++argIdx) { | |||
395 | ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); | |||
396 | if (Param->hasUnparsedDefaultArg()) { | |||
397 | std::unique_ptr<CachedTokens> Toks = | |||
398 | std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); | |||
399 | SourceRange SR; | |||
400 | if (Toks->size() > 1) | |||
401 | SR = SourceRange((*Toks)[1].getLocation(), | |||
402 | Toks->back().getLocation()); | |||
403 | else | |||
404 | SR = UnparsedDefaultArgLocs[Param]; | |||
405 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) | |||
406 | << SR; | |||
407 | } else if (Param->getDefaultArg()) { | |||
408 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) | |||
409 | << Param->getDefaultArg()->getSourceRange(); | |||
410 | Param->setDefaultArg(nullptr); | |||
411 | } | |||
412 | } | |||
413 | } else if (chunk.Kind != DeclaratorChunk::Paren) { | |||
414 | MightBeFunction = false; | |||
415 | } | |||
416 | } | |||
417 | } | |||
418 | ||||
419 | static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { | |||
420 | for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { | |||
421 | const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); | |||
422 | if (!PVD->hasDefaultArg()) | |||
423 | return false; | |||
424 | if (!PVD->hasInheritedDefaultArg()) | |||
425 | return true; | |||
426 | } | |||
427 | return false; | |||
428 | } | |||
429 | ||||
430 | /// MergeCXXFunctionDecl - Merge two declarations of the same C++ | |||
431 | /// function, once we already know that they have the same | |||
432 | /// type. Subroutine of MergeFunctionDecl. Returns true if there was an | |||
433 | /// error, false otherwise. | |||
434 | bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, | |||
435 | Scope *S) { | |||
436 | bool Invalid = false; | |||
437 | ||||
438 | // The declaration context corresponding to the scope is the semantic | |||
439 | // parent, unless this is a local function declaration, in which case | |||
440 | // it is that surrounding function. | |||
441 | DeclContext *ScopeDC = New->isLocalExternDecl() | |||
442 | ? New->getLexicalDeclContext() | |||
443 | : New->getDeclContext(); | |||
444 | ||||
445 | // Find the previous declaration for the purpose of default arguments. | |||
446 | FunctionDecl *PrevForDefaultArgs = Old; | |||
447 | for (/**/; PrevForDefaultArgs; | |||
448 | // Don't bother looking back past the latest decl if this is a local | |||
449 | // extern declaration; nothing else could work. | |||
450 | PrevForDefaultArgs = New->isLocalExternDecl() | |||
451 | ? nullptr | |||
452 | : PrevForDefaultArgs->getPreviousDecl()) { | |||
453 | // Ignore hidden declarations. | |||
454 | if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) | |||
455 | continue; | |||
456 | ||||
457 | if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && | |||
458 | !New->isCXXClassMember()) { | |||
459 | // Ignore default arguments of old decl if they are not in | |||
460 | // the same scope and this is not an out-of-line definition of | |||
461 | // a member function. | |||
462 | continue; | |||
463 | } | |||
464 | ||||
465 | if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { | |||
466 | // If only one of these is a local function declaration, then they are | |||
467 | // declared in different scopes, even though isDeclInScope may think | |||
468 | // they're in the same scope. (If both are local, the scope check is | |||
469 | // sufficient, and if neither is local, then they are in the same scope.) | |||
470 | continue; | |||
471 | } | |||
472 | ||||
473 | // We found the right previous declaration. | |||
474 | break; | |||
475 | } | |||
476 | ||||
477 | // C++ [dcl.fct.default]p4: | |||
478 | // For non-template functions, default arguments can be added in | |||
479 | // later declarations of a function in the same | |||
480 | // scope. Declarations in different scopes have completely | |||
481 | // distinct sets of default arguments. That is, declarations in | |||
482 | // inner scopes do not acquire default arguments from | |||
483 | // declarations in outer scopes, and vice versa. In a given | |||
484 | // function declaration, all parameters subsequent to a | |||
485 | // parameter with a default argument shall have default | |||
486 | // arguments supplied in this or previous declarations. A | |||
487 | // default argument shall not be redefined by a later | |||
488 | // declaration (not even to the same value). | |||
489 | // | |||
490 | // C++ [dcl.fct.default]p6: | |||
491 | // Except for member functions of class templates, the default arguments | |||
492 | // in a member function definition that appears outside of the class | |||
493 | // definition are added to the set of default arguments provided by the | |||
494 | // member function declaration in the class definition. | |||
495 | for (unsigned p = 0, NumParams = PrevForDefaultArgs | |||
496 | ? PrevForDefaultArgs->getNumParams() | |||
497 | : 0; | |||
498 | p < NumParams; ++p) { | |||
499 | ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); | |||
500 | ParmVarDecl *NewParam = New->getParamDecl(p); | |||
501 | ||||
502 | bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; | |||
503 | bool NewParamHasDfl = NewParam->hasDefaultArg(); | |||
504 | ||||
505 | if (OldParamHasDfl && NewParamHasDfl) { | |||
506 | unsigned DiagDefaultParamID = | |||
507 | diag::err_param_default_argument_redefinition; | |||
508 | ||||
509 | // MSVC accepts that default parameters be redefined for member functions | |||
510 | // of template class. The new default parameter's value is ignored. | |||
511 | Invalid = true; | |||
512 | if (getLangOpts().MicrosoftExt) { | |||
513 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); | |||
514 | if (MD && MD->getParent()->getDescribedClassTemplate()) { | |||
515 | // Merge the old default argument into the new parameter. | |||
516 | NewParam->setHasInheritedDefaultArg(); | |||
517 | if (OldParam->hasUninstantiatedDefaultArg()) | |||
518 | NewParam->setUninstantiatedDefaultArg( | |||
519 | OldParam->getUninstantiatedDefaultArg()); | |||
520 | else | |||
521 | NewParam->setDefaultArg(OldParam->getInit()); | |||
522 | DiagDefaultParamID = diag::ext_param_default_argument_redefinition; | |||
523 | Invalid = false; | |||
524 | } | |||
525 | } | |||
526 | ||||
527 | // FIXME: If we knew where the '=' was, we could easily provide a fix-it | |||
528 | // hint here. Alternatively, we could walk the type-source information | |||
529 | // for NewParam to find the last source location in the type... but it | |||
530 | // isn't worth the effort right now. This is the kind of test case that | |||
531 | // is hard to get right: | |||
532 | // int f(int); | |||
533 | // void g(int (*fp)(int) = f); | |||
534 | // void g(int (*fp)(int) = &f); | |||
535 | Diag(NewParam->getLocation(), DiagDefaultParamID) | |||
536 | << NewParam->getDefaultArgRange(); | |||
537 | ||||
538 | // Look for the function declaration where the default argument was | |||
539 | // actually written, which may be a declaration prior to Old. | |||
540 | for (auto Older = PrevForDefaultArgs; | |||
541 | OldParam->hasInheritedDefaultArg(); /**/) { | |||
542 | Older = Older->getPreviousDecl(); | |||
543 | OldParam = Older->getParamDecl(p); | |||
544 | } | |||
545 | ||||
546 | Diag(OldParam->getLocation(), diag::note_previous_definition) | |||
547 | << OldParam->getDefaultArgRange(); | |||
548 | } else if (OldParamHasDfl) { | |||
549 | // Merge the old default argument into the new parameter unless the new | |||
550 | // function is a friend declaration in a template class. In the latter | |||
551 | // case the default arguments will be inherited when the friend | |||
552 | // declaration will be instantiated. | |||
553 | if (New->getFriendObjectKind() == Decl::FOK_None || | |||
554 | !New->getLexicalDeclContext()->isDependentContext()) { | |||
555 | // It's important to use getInit() here; getDefaultArg() | |||
556 | // strips off any top-level ExprWithCleanups. | |||
557 | NewParam->setHasInheritedDefaultArg(); | |||
558 | if (OldParam->hasUnparsedDefaultArg()) | |||
559 | NewParam->setUnparsedDefaultArg(); | |||
560 | else if (OldParam->hasUninstantiatedDefaultArg()) | |||
561 | NewParam->setUninstantiatedDefaultArg( | |||
562 | OldParam->getUninstantiatedDefaultArg()); | |||
563 | else | |||
564 | NewParam->setDefaultArg(OldParam->getInit()); | |||
565 | } | |||
566 | } else if (NewParamHasDfl) { | |||
567 | if (New->getDescribedFunctionTemplate()) { | |||
568 | // Paragraph 4, quoted above, only applies to non-template functions. | |||
569 | Diag(NewParam->getLocation(), | |||
570 | diag::err_param_default_argument_template_redecl) | |||
571 | << NewParam->getDefaultArgRange(); | |||
572 | Diag(PrevForDefaultArgs->getLocation(), | |||
573 | diag::note_template_prev_declaration) | |||
574 | << false; | |||
575 | } else if (New->getTemplateSpecializationKind() | |||
576 | != TSK_ImplicitInstantiation && | |||
577 | New->getTemplateSpecializationKind() != TSK_Undeclared) { | |||
578 | // C++ [temp.expr.spec]p21: | |||
579 | // Default function arguments shall not be specified in a declaration | |||
580 | // or a definition for one of the following explicit specializations: | |||
581 | // - the explicit specialization of a function template; | |||
582 | // - the explicit specialization of a member function template; | |||
583 | // - the explicit specialization of a member function of a class | |||
584 | // template where the class template specialization to which the | |||
585 | // member function specialization belongs is implicitly | |||
586 | // instantiated. | |||
587 | Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) | |||
588 | << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) | |||
589 | << New->getDeclName() | |||
590 | << NewParam->getDefaultArgRange(); | |||
591 | } else if (New->getDeclContext()->isDependentContext()) { | |||
592 | // C++ [dcl.fct.default]p6 (DR217): | |||
593 | // Default arguments for a member function of a class template shall | |||
594 | // be specified on the initial declaration of the member function | |||
595 | // within the class template. | |||
596 | // | |||
597 | // Reading the tea leaves a bit in DR217 and its reference to DR205 | |||
598 | // leads me to the conclusion that one cannot add default function | |||
599 | // arguments for an out-of-line definition of a member function of a | |||
600 | // dependent type. | |||
601 | int WhichKind = 2; | |||
602 | if (CXXRecordDecl *Record | |||
603 | = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { | |||
604 | if (Record->getDescribedClassTemplate()) | |||
605 | WhichKind = 0; | |||
606 | else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) | |||
607 | WhichKind = 1; | |||
608 | else | |||
609 | WhichKind = 2; | |||
610 | } | |||
611 | ||||
612 | Diag(NewParam->getLocation(), | |||
613 | diag::err_param_default_argument_member_template_redecl) | |||
614 | << WhichKind | |||
615 | << NewParam->getDefaultArgRange(); | |||
616 | } | |||
617 | } | |||
618 | } | |||
619 | ||||
620 | // DR1344: If a default argument is added outside a class definition and that | |||
621 | // default argument makes the function a special member function, the program | |||
622 | // is ill-formed. This can only happen for constructors. | |||
623 | if (isa<CXXConstructorDecl>(New) && | |||
624 | New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { | |||
625 | CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), | |||
626 | OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); | |||
627 | if (NewSM != OldSM) { | |||
628 | ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); | |||
629 | assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0) : __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 629, __PRETTY_FUNCTION__)); | |||
630 | Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) | |||
631 | << NewParam->getDefaultArgRange() << NewSM; | |||
632 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
633 | } | |||
634 | } | |||
635 | ||||
636 | const FunctionDecl *Def; | |||
637 | // C++11 [dcl.constexpr]p1: If any declaration of a function or function | |||
638 | // template has a constexpr specifier then all its declarations shall | |||
639 | // contain the constexpr specifier. | |||
640 | if (New->isConstexpr() != Old->isConstexpr()) { | |||
641 | Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) | |||
642 | << New << New->isConstexpr(); | |||
643 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
644 | Invalid = true; | |||
645 | } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && | |||
646 | Old->isDefined(Def) && | |||
647 | // If a friend function is inlined but does not have 'inline' | |||
648 | // specifier, it is a definition. Do not report attribute conflict | |||
649 | // in this case, redefinition will be diagnosed later. | |||
650 | (New->isInlineSpecified() || | |||
651 | New->getFriendObjectKind() == Decl::FOK_None)) { | |||
652 | // C++11 [dcl.fcn.spec]p4: | |||
653 | // If the definition of a function appears in a translation unit before its | |||
654 | // first declaration as inline, the program is ill-formed. | |||
655 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | |||
656 | Diag(Def->getLocation(), diag::note_previous_definition); | |||
657 | Invalid = true; | |||
658 | } | |||
659 | ||||
660 | // C++17 [temp.deduct.guide]p3: | |||
661 | // Two deduction guide declarations in the same translation unit | |||
662 | // for the same class template shall not have equivalent | |||
663 | // parameter-declaration-clauses. | |||
664 | if (isa<CXXDeductionGuideDecl>(New) && | |||
665 | !New->isFunctionTemplateSpecialization()) { | |||
666 | Diag(New->getLocation(), diag::err_deduction_guide_redeclared); | |||
667 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
668 | } | |||
669 | ||||
670 | // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default | |||
671 | // argument expression, that declaration shall be a definition and shall be | |||
672 | // the only declaration of the function or function template in the | |||
673 | // translation unit. | |||
674 | if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && | |||
675 | functionDeclHasDefaultArgument(Old)) { | |||
676 | Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); | |||
677 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
678 | Invalid = true; | |||
679 | } | |||
680 | ||||
681 | return Invalid; | |||
682 | } | |||
683 | ||||
684 | NamedDecl * | |||
685 | Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, | |||
686 | MultiTemplateParamsArg TemplateParamLists) { | |||
687 | assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0 ) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 687, __PRETTY_FUNCTION__)); | |||
688 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | |||
689 | ||||
690 | // The syntax only allows a decomposition declarator as a simple-declaration, | |||
691 | // a for-range-declaration, or a condition in Clang, but we parse it in more | |||
692 | // cases than that. | |||
693 | if (!D.mayHaveDecompositionDeclarator()) { | |||
694 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | |||
695 | << Decomp.getSourceRange(); | |||
696 | return nullptr; | |||
697 | } | |||
698 | ||||
699 | if (!TemplateParamLists.empty()) { | |||
700 | // FIXME: There's no rule against this, but there are also no rules that | |||
701 | // would actually make it usable, so we reject it for now. | |||
702 | Diag(TemplateParamLists.front()->getTemplateLoc(), | |||
703 | diag::err_decomp_decl_template); | |||
704 | return nullptr; | |||
705 | } | |||
706 | ||||
707 | Diag(Decomp.getLSquareLoc(), | |||
708 | !getLangOpts().CPlusPlus17 | |||
709 | ? diag::ext_decomp_decl | |||
710 | : D.getContext() == DeclaratorContext::ConditionContext | |||
711 | ? diag::ext_decomp_decl_cond | |||
712 | : diag::warn_cxx14_compat_decomp_decl) | |||
713 | << Decomp.getSourceRange(); | |||
714 | ||||
715 | // The semantic context is always just the current context. | |||
716 | DeclContext *const DC = CurContext; | |||
717 | ||||
718 | // C++1z [dcl.dcl]/8: | |||
719 | // The decl-specifier-seq shall contain only the type-specifier auto | |||
720 | // and cv-qualifiers. | |||
721 | auto &DS = D.getDeclSpec(); | |||
722 | { | |||
723 | SmallVector<StringRef, 8> BadSpecifiers; | |||
724 | SmallVector<SourceLocation, 8> BadSpecifierLocs; | |||
725 | if (auto SCS = DS.getStorageClassSpec()) { | |||
726 | BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); | |||
727 | BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); | |||
728 | } | |||
729 | if (auto TSCS = DS.getThreadStorageClassSpec()) { | |||
730 | BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); | |||
731 | BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); | |||
732 | } | |||
733 | if (DS.isConstexprSpecified()) { | |||
734 | BadSpecifiers.push_back("constexpr"); | |||
735 | BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); | |||
736 | } | |||
737 | if (DS.isInlineSpecified()) { | |||
738 | BadSpecifiers.push_back("inline"); | |||
739 | BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); | |||
740 | } | |||
741 | if (!BadSpecifiers.empty()) { | |||
742 | auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); | |||
743 | Err << (int)BadSpecifiers.size() | |||
744 | << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); | |||
745 | // Don't add FixItHints to remove the specifiers; we do still respect | |||
746 | // them when building the underlying variable. | |||
747 | for (auto Loc : BadSpecifierLocs) | |||
748 | Err << SourceRange(Loc, Loc); | |||
749 | } | |||
750 | // We can't recover from it being declared as a typedef. | |||
751 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
752 | return nullptr; | |||
753 | } | |||
754 | ||||
755 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
756 | QualType R = TInfo->getType(); | |||
757 | ||||
758 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
759 | UPPC_DeclarationType)) | |||
760 | D.setInvalidType(); | |||
761 | ||||
762 | // The syntax only allows a single ref-qualifier prior to the decomposition | |||
763 | // declarator. No other declarator chunks are permitted. Also check the type | |||
764 | // specifier here. | |||
765 | if (DS.getTypeSpecType() != DeclSpec::TST_auto || | |||
766 | D.hasGroupingParens() || D.getNumTypeObjects() > 1 || | |||
767 | (D.getNumTypeObjects() == 1 && | |||
768 | D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { | |||
769 | Diag(Decomp.getLSquareLoc(), | |||
770 | (D.hasGroupingParens() || | |||
771 | (D.getNumTypeObjects() && | |||
772 | D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) | |||
773 | ? diag::err_decomp_decl_parens | |||
774 | : diag::err_decomp_decl_type) | |||
775 | << R; | |||
776 | ||||
777 | // In most cases, there's no actual problem with an explicitly-specified | |||
778 | // type, but a function type won't work here, and ActOnVariableDeclarator | |||
779 | // shouldn't be called for such a type. | |||
780 | if (R->isFunctionType()) | |||
781 | D.setInvalidType(); | |||
782 | } | |||
783 | ||||
784 | // Build the BindingDecls. | |||
785 | SmallVector<BindingDecl*, 8> Bindings; | |||
786 | ||||
787 | // Build the BindingDecls. | |||
788 | for (auto &B : D.getDecompositionDeclarator().bindings()) { | |||
789 | // Check for name conflicts. | |||
790 | DeclarationNameInfo NameInfo(B.Name, B.NameLoc); | |||
791 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
792 | ForVisibleRedeclaration); | |||
793 | LookupName(Previous, S, | |||
794 | /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); | |||
795 | ||||
796 | // It's not permitted to shadow a template parameter name. | |||
797 | if (Previous.isSingleResult() && | |||
798 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
799 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | |||
800 | Previous.getFoundDecl()); | |||
801 | Previous.clear(); | |||
802 | } | |||
803 | ||||
804 | bool ConsiderLinkage = DC->isFunctionOrMethod() && | |||
805 | DS.getStorageClassSpec() == DeclSpec::SCS_extern; | |||
806 | FilterLookupForScope(Previous, DC, S, ConsiderLinkage, | |||
807 | /*AllowInlineNamespace*/false); | |||
808 | if (!Previous.empty()) { | |||
809 | auto *Old = Previous.getRepresentativeDecl(); | |||
810 | Diag(B.NameLoc, diag::err_redefinition) << B.Name; | |||
811 | Diag(Old->getLocation(), diag::note_previous_definition); | |||
812 | } | |||
813 | ||||
814 | auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); | |||
815 | PushOnScopeChains(BD, S, true); | |||
816 | Bindings.push_back(BD); | |||
817 | ParsingInitForAutoVars.insert(BD); | |||
818 | } | |||
819 | ||||
820 | // There are no prior lookup results for the variable itself, because it | |||
821 | // is unnamed. | |||
822 | DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, | |||
823 | Decomp.getLSquareLoc()); | |||
824 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
825 | ForVisibleRedeclaration); | |||
826 | ||||
827 | // Build the variable that holds the non-decomposed object. | |||
828 | bool AddToScope = true; | |||
829 | NamedDecl *New = | |||
830 | ActOnVariableDeclarator(S, D, DC, TInfo, Previous, | |||
831 | MultiTemplateParamsArg(), AddToScope, Bindings); | |||
832 | if (AddToScope) { | |||
833 | S->AddDecl(New); | |||
834 | CurContext->addHiddenDecl(New); | |||
835 | } | |||
836 | ||||
837 | if (isInOpenMPDeclareTargetContext()) | |||
838 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | |||
839 | ||||
840 | return New; | |||
841 | } | |||
842 | ||||
843 | static bool checkSimpleDecomposition( | |||
844 | Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, | |||
845 | QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, | |||
846 | llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { | |||
847 | if ((int64_t)Bindings.size() != NumElems) { | |||
848 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | |||
849 | << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) | |||
850 | << (NumElems < Bindings.size()); | |||
851 | return true; | |||
852 | } | |||
853 | ||||
854 | unsigned I = 0; | |||
855 | for (auto *B : Bindings) { | |||
856 | SourceLocation Loc = B->getLocation(); | |||
857 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | |||
858 | if (E.isInvalid()) | |||
859 | return true; | |||
860 | E = GetInit(Loc, E.get(), I++); | |||
861 | if (E.isInvalid()) | |||
862 | return true; | |||
863 | B->setBinding(ElemType, E.get()); | |||
864 | } | |||
865 | ||||
866 | return false; | |||
867 | } | |||
868 | ||||
869 | static bool checkArrayLikeDecomposition(Sema &S, | |||
870 | ArrayRef<BindingDecl *> Bindings, | |||
871 | ValueDecl *Src, QualType DecompType, | |||
872 | const llvm::APSInt &NumElems, | |||
873 | QualType ElemType) { | |||
874 | return checkSimpleDecomposition( | |||
875 | S, Bindings, Src, DecompType, NumElems, ElemType, | |||
876 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { | |||
877 | ExprResult E = S.ActOnIntegerConstant(Loc, I); | |||
878 | if (E.isInvalid()) | |||
879 | return ExprError(); | |||
880 | return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); | |||
881 | }); | |||
882 | } | |||
883 | ||||
884 | static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | |||
885 | ValueDecl *Src, QualType DecompType, | |||
886 | const ConstantArrayType *CAT) { | |||
887 | return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, | |||
888 | llvm::APSInt(CAT->getSize()), | |||
889 | CAT->getElementType()); | |||
890 | } | |||
891 | ||||
892 | static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | |||
893 | ValueDecl *Src, QualType DecompType, | |||
894 | const VectorType *VT) { | |||
895 | return checkArrayLikeDecomposition( | |||
896 | S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), | |||
897 | S.Context.getQualifiedType(VT->getElementType(), | |||
898 | DecompType.getQualifiers())); | |||
899 | } | |||
900 | ||||
901 | static bool checkComplexDecomposition(Sema &S, | |||
902 | ArrayRef<BindingDecl *> Bindings, | |||
903 | ValueDecl *Src, QualType DecompType, | |||
904 | const ComplexType *CT) { | |||
905 | return checkSimpleDecomposition( | |||
906 | S, Bindings, Src, DecompType, llvm::APSInt::get(2), | |||
907 | S.Context.getQualifiedType(CT->getElementType(), | |||
908 | DecompType.getQualifiers()), | |||
909 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { | |||
910 | return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); | |||
911 | }); | |||
912 | } | |||
913 | ||||
914 | static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, | |||
915 | TemplateArgumentListInfo &Args) { | |||
916 | SmallString<128> SS; | |||
917 | llvm::raw_svector_ostream OS(SS); | |||
918 | bool First = true; | |||
919 | for (auto &Arg : Args.arguments()) { | |||
920 | if (!First) | |||
921 | OS << ", "; | |||
922 | Arg.getArgument().print(PrintingPolicy, OS); | |||
923 | First = false; | |||
924 | } | |||
925 | return OS.str(); | |||
926 | } | |||
927 | ||||
928 | static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, | |||
929 | SourceLocation Loc, StringRef Trait, | |||
930 | TemplateArgumentListInfo &Args, | |||
931 | unsigned DiagID) { | |||
932 | auto DiagnoseMissing = [&] { | |||
933 | if (DiagID) | |||
934 | S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), | |||
935 | Args); | |||
936 | return true; | |||
937 | }; | |||
938 | ||||
939 | // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. | |||
940 | NamespaceDecl *Std = S.getStdNamespace(); | |||
941 | if (!Std) | |||
942 | return DiagnoseMissing(); | |||
943 | ||||
944 | // Look up the trait itself, within namespace std. We can diagnose various | |||
945 | // problems with this lookup even if we've been asked to not diagnose a | |||
946 | // missing specialization, because this can only fail if the user has been | |||
947 | // declaring their own names in namespace std or we don't support the | |||
948 | // standard library implementation in use. | |||
949 | LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), | |||
950 | Loc, Sema::LookupOrdinaryName); | |||
951 | if (!S.LookupQualifiedName(Result, Std)) | |||
952 | return DiagnoseMissing(); | |||
953 | if (Result.isAmbiguous()) | |||
954 | return true; | |||
955 | ||||
956 | ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); | |||
957 | if (!TraitTD) { | |||
958 | Result.suppressDiagnostics(); | |||
959 | NamedDecl *Found = *Result.begin(); | |||
960 | S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; | |||
961 | S.Diag(Found->getLocation(), diag::note_declared_at); | |||
962 | return true; | |||
963 | } | |||
964 | ||||
965 | // Build the template-id. | |||
966 | QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); | |||
967 | if (TraitTy.isNull()) | |||
968 | return true; | |||
969 | if (!S.isCompleteType(Loc, TraitTy)) { | |||
970 | if (DiagID) | |||
971 | S.RequireCompleteType( | |||
972 | Loc, TraitTy, DiagID, | |||
973 | printTemplateArgs(S.Context.getPrintingPolicy(), Args)); | |||
974 | return true; | |||
975 | } | |||
976 | ||||
977 | CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); | |||
978 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 978, __PRETTY_FUNCTION__)); | |||
979 | ||||
980 | // Look up the member of the trait type. | |||
981 | S.LookupQualifiedName(TraitMemberLookup, RD); | |||
982 | return TraitMemberLookup.isAmbiguous(); | |||
983 | } | |||
984 | ||||
985 | static TemplateArgumentLoc | |||
986 | getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, | |||
987 | uint64_t I) { | |||
988 | TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); | |||
989 | return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); | |||
990 | } | |||
991 | ||||
992 | static TemplateArgumentLoc | |||
993 | getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { | |||
994 | return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); | |||
995 | } | |||
996 | ||||
997 | namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } | |||
998 | ||||
999 | static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, | |||
1000 | llvm::APSInt &Size) { | |||
1001 | EnterExpressionEvaluationContext ContextRAII( | |||
1002 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | |||
1003 | ||||
1004 | DeclarationName Value = S.PP.getIdentifierInfo("value"); | |||
1005 | LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); | |||
1006 | ||||
1007 | // Form template argument list for tuple_size<T>. | |||
1008 | TemplateArgumentListInfo Args(Loc, Loc); | |||
1009 | Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); | |||
1010 | ||||
1011 | // If there's no tuple_size specialization, it's not tuple-like. | |||
1012 | if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) | |||
1013 | return IsTupleLike::NotTupleLike; | |||
1014 | ||||
1015 | // If we get this far, we've committed to the tuple interpretation, but | |||
1016 | // we can still fail if there actually isn't a usable ::value. | |||
1017 | ||||
1018 | struct ICEDiagnoser : Sema::VerifyICEDiagnoser { | |||
1019 | LookupResult &R; | |||
1020 | TemplateArgumentListInfo &Args; | |||
1021 | ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) | |||
1022 | : R(R), Args(Args) {} | |||
1023 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { | |||
1024 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) | |||
1025 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args); | |||
1026 | } | |||
1027 | } Diagnoser(R, Args); | |||
1028 | ||||
1029 | if (R.empty()) { | |||
1030 | Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); | |||
1031 | return IsTupleLike::Error; | |||
1032 | } | |||
1033 | ||||
1034 | ExprResult E = | |||
1035 | S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); | |||
1036 | if (E.isInvalid()) | |||
1037 | return IsTupleLike::Error; | |||
1038 | ||||
1039 | E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); | |||
1040 | if (E.isInvalid()) | |||
1041 | return IsTupleLike::Error; | |||
1042 | ||||
1043 | return IsTupleLike::TupleLike; | |||
1044 | } | |||
1045 | ||||
1046 | /// \return std::tuple_element<I, T>::type. | |||
1047 | static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, | |||
1048 | unsigned I, QualType T) { | |||
1049 | // Form template argument list for tuple_element<I, T>. | |||
1050 | TemplateArgumentListInfo Args(Loc, Loc); | |||
1051 | Args.addArgument( | |||
1052 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); | |||
1053 | Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); | |||
1054 | ||||
1055 | DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); | |||
1056 | LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); | |||
1057 | if (lookupStdTypeTraitMember( | |||
1058 | S, R, Loc, "tuple_element", Args, | |||
1059 | diag::err_decomp_decl_std_tuple_element_not_specialized)) | |||
1060 | return QualType(); | |||
1061 | ||||
1062 | auto *TD = R.getAsSingle<TypeDecl>(); | |||
1063 | if (!TD) { | |||
1064 | R.suppressDiagnostics(); | |||
1065 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) | |||
1066 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args); | |||
1067 | if (!R.empty()) | |||
1068 | S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); | |||
1069 | return QualType(); | |||
1070 | } | |||
1071 | ||||
1072 | return S.Context.getTypeDeclType(TD); | |||
1073 | } | |||
1074 | ||||
1075 | namespace { | |||
1076 | struct BindingDiagnosticTrap { | |||
1077 | Sema &S; | |||
1078 | DiagnosticErrorTrap Trap; | |||
1079 | BindingDecl *BD; | |||
1080 | ||||
1081 | BindingDiagnosticTrap(Sema &S, BindingDecl *BD) | |||
1082 | : S(S), Trap(S.Diags), BD(BD) {} | |||
1083 | ~BindingDiagnosticTrap() { | |||
1084 | if (Trap.hasErrorOccurred()) | |||
1085 | S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; | |||
1086 | } | |||
1087 | }; | |||
1088 | } | |||
1089 | ||||
1090 | static bool checkTupleLikeDecomposition(Sema &S, | |||
1091 | ArrayRef<BindingDecl *> Bindings, | |||
1092 | VarDecl *Src, QualType DecompType, | |||
1093 | const llvm::APSInt &TupleSize) { | |||
1094 | if ((int64_t)Bindings.size() != TupleSize) { | |||
1095 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | |||
1096 | << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) | |||
1097 | << (TupleSize < Bindings.size()); | |||
1098 | return true; | |||
1099 | } | |||
1100 | ||||
1101 | if (Bindings.empty()) | |||
1102 | return false; | |||
1103 | ||||
1104 | DeclarationName GetDN = S.PP.getIdentifierInfo("get"); | |||
1105 | ||||
1106 | // [dcl.decomp]p3: | |||
1107 | // The unqualified-id get is looked up in the scope of E by class member | |||
1108 | // access lookup ... | |||
1109 | LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); | |||
1110 | bool UseMemberGet = false; | |||
1111 | if (S.isCompleteType(Src->getLocation(), DecompType)) { | |||
1112 | if (auto *RD = DecompType->getAsCXXRecordDecl()) | |||
1113 | S.LookupQualifiedName(MemberGet, RD); | |||
1114 | if (MemberGet.isAmbiguous()) | |||
1115 | return true; | |||
1116 | // ... and if that finds at least one declaration that is a function | |||
1117 | // template whose first template parameter is a non-type parameter ... | |||
1118 | for (NamedDecl *D : MemberGet) { | |||
1119 | if (FunctionTemplateDecl *FTD = | |||
1120 | dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { | |||
1121 | TemplateParameterList *TPL = FTD->getTemplateParameters(); | |||
1122 | if (TPL->size() != 0 && | |||
1123 | isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { | |||
1124 | // ... the initializer is e.get<i>(). | |||
1125 | UseMemberGet = true; | |||
1126 | break; | |||
1127 | } | |||
1128 | } | |||
1129 | } | |||
1130 | } | |||
1131 | ||||
1132 | unsigned I = 0; | |||
1133 | for (auto *B : Bindings) { | |||
1134 | BindingDiagnosticTrap Trap(S, B); | |||
1135 | SourceLocation Loc = B->getLocation(); | |||
1136 | ||||
1137 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | |||
1138 | if (E.isInvalid()) | |||
1139 | return true; | |||
1140 | ||||
1141 | // e is an lvalue if the type of the entity is an lvalue reference and | |||
1142 | // an xvalue otherwise | |||
1143 | if (!Src->getType()->isLValueReferenceType()) | |||
1144 | E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, | |||
1145 | E.get(), nullptr, VK_XValue); | |||
1146 | ||||
1147 | TemplateArgumentListInfo Args(Loc, Loc); | |||
1148 | Args.addArgument( | |||
1149 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); | |||
1150 | ||||
1151 | if (UseMemberGet) { | |||
1152 | // if [lookup of member get] finds at least one declaration, the | |||
1153 | // initializer is e.get<i-1>(). | |||
1154 | E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, | |||
1155 | CXXScopeSpec(), SourceLocation(), nullptr, | |||
1156 | MemberGet, &Args, nullptr); | |||
1157 | if (E.isInvalid()) | |||
1158 | return true; | |||
1159 | ||||
1160 | E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); | |||
1161 | } else { | |||
1162 | // Otherwise, the initializer is get<i-1>(e), where get is looked up | |||
1163 | // in the associated namespaces. | |||
1164 | Expr *Get = UnresolvedLookupExpr::Create( | |||
1165 | S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), | |||
1166 | DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, | |||
1167 | UnresolvedSetIterator(), UnresolvedSetIterator()); | |||
1168 | ||||
1169 | Expr *Arg = E.get(); | |||
1170 | E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); | |||
1171 | } | |||
1172 | if (E.isInvalid()) | |||
1173 | return true; | |||
1174 | Expr *Init = E.get(); | |||
1175 | ||||
1176 | // Given the type T designated by std::tuple_element<i - 1, E>::type, | |||
1177 | QualType T = getTupleLikeElementType(S, Loc, I, DecompType); | |||
1178 | if (T.isNull()) | |||
1179 | return true; | |||
1180 | ||||
1181 | // each vi is a variable of type "reference to T" initialized with the | |||
1182 | // initializer, where the reference is an lvalue reference if the | |||
1183 | // initializer is an lvalue and an rvalue reference otherwise | |||
1184 | QualType RefType = | |||
1185 | S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); | |||
1186 | if (RefType.isNull()) | |||
1187 | return true; | |||
1188 | auto *RefVD = VarDecl::Create( | |||
1189 | S.Context, Src->getDeclContext(), Loc, Loc, | |||
1190 | B->getDeclName().getAsIdentifierInfo(), RefType, | |||
1191 | S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); | |||
1192 | RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); | |||
1193 | RefVD->setTSCSpec(Src->getTSCSpec()); | |||
1194 | RefVD->setImplicit(); | |||
1195 | if (Src->isInlineSpecified()) | |||
1196 | RefVD->setInlineSpecified(); | |||
1197 | RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); | |||
1198 | ||||
1199 | InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); | |||
1200 | InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); | |||
1201 | InitializationSequence Seq(S, Entity, Kind, Init); | |||
1202 | E = Seq.Perform(S, Entity, Kind, Init); | |||
1203 | if (E.isInvalid()) | |||
1204 | return true; | |||
1205 | E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); | |||
1206 | if (E.isInvalid()) | |||
1207 | return true; | |||
1208 | RefVD->setInit(E.get()); | |||
1209 | RefVD->checkInitIsICE(); | |||
1210 | ||||
1211 | E = S.BuildDeclarationNameExpr(CXXScopeSpec(), | |||
1212 | DeclarationNameInfo(B->getDeclName(), Loc), | |||
1213 | RefVD); | |||
1214 | if (E.isInvalid()) | |||
1215 | return true; | |||
1216 | ||||
1217 | B->setBinding(T, E.get()); | |||
1218 | I++; | |||
1219 | } | |||
1220 | ||||
1221 | return false; | |||
1222 | } | |||
1223 | ||||
1224 | /// Find the base class to decompose in a built-in decomposition of a class type. | |||
1225 | /// This base class search is, unfortunately, not quite like any other that we | |||
1226 | /// perform anywhere else in C++. | |||
1227 | static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, | |||
1228 | const CXXRecordDecl *RD, | |||
1229 | CXXCastPath &BasePath) { | |||
1230 | auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, | |||
1231 | CXXBasePath &Path) { | |||
1232 | return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); | |||
1233 | }; | |||
1234 | ||||
1235 | const CXXRecordDecl *ClassWithFields = nullptr; | |||
1236 | AccessSpecifier AS = AS_public; | |||
1237 | if (RD->hasDirectFields()) | |||
1238 | // [dcl.decomp]p4: | |||
1239 | // Otherwise, all of E's non-static data members shall be public direct | |||
1240 | // members of E ... | |||
1241 | ClassWithFields = RD; | |||
1242 | else { | |||
1243 | // ... or of ... | |||
1244 | CXXBasePaths Paths; | |||
1245 | Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); | |||
1246 | if (!RD->lookupInBases(BaseHasFields, Paths)) { | |||
1247 | // If no classes have fields, just decompose RD itself. (This will work | |||
1248 | // if and only if zero bindings were provided.) | |||
1249 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); | |||
1250 | } | |||
1251 | ||||
1252 | CXXBasePath *BestPath = nullptr; | |||
1253 | for (auto &P : Paths) { | |||
1254 | if (!BestPath) | |||
1255 | BestPath = &P; | |||
1256 | else if (!S.Context.hasSameType(P.back().Base->getType(), | |||
1257 | BestPath->back().Base->getType())) { | |||
1258 | // ... the same ... | |||
1259 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) | |||
1260 | << false << RD << BestPath->back().Base->getType() | |||
1261 | << P.back().Base->getType(); | |||
1262 | return DeclAccessPair(); | |||
1263 | } else if (P.Access < BestPath->Access) { | |||
1264 | BestPath = &P; | |||
1265 | } | |||
1266 | } | |||
1267 | ||||
1268 | // ... unambiguous ... | |||
1269 | QualType BaseType = BestPath->back().Base->getType(); | |||
1270 | if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { | |||
1271 | S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) | |||
1272 | << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); | |||
1273 | return DeclAccessPair(); | |||
1274 | } | |||
1275 | ||||
1276 | // ... [accessible, implied by other rules] base class of E. | |||
1277 | S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), | |||
1278 | *BestPath, diag::err_decomp_decl_inaccessible_base); | |||
1279 | AS = BestPath->Access; | |||
1280 | ||||
1281 | ClassWithFields = BaseType->getAsCXXRecordDecl(); | |||
1282 | S.BuildBasePathArray(Paths, BasePath); | |||
1283 | } | |||
1284 | ||||
1285 | // The above search did not check whether the selected class itself has base | |||
1286 | // classes with fields, so check that now. | |||
1287 | CXXBasePaths Paths; | |||
1288 | if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { | |||
1289 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) | |||
1290 | << (ClassWithFields == RD) << RD << ClassWithFields | |||
1291 | << Paths.front().back().Base->getType(); | |||
1292 | return DeclAccessPair(); | |||
1293 | } | |||
1294 | ||||
1295 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); | |||
1296 | } | |||
1297 | ||||
1298 | static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | |||
1299 | ValueDecl *Src, QualType DecompType, | |||
1300 | const CXXRecordDecl *OrigRD) { | |||
1301 | if (S.RequireCompleteType(Src->getLocation(), DecompType, | |||
1302 | diag::err_incomplete_type)) | |||
1303 | return true; | |||
1304 | ||||
1305 | CXXCastPath BasePath; | |||
1306 | DeclAccessPair BasePair = | |||
1307 | findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); | |||
1308 | const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); | |||
1309 | if (!RD) | |||
1310 | return true; | |||
1311 | QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), | |||
1312 | DecompType.getQualifiers()); | |||
1313 | ||||
1314 | auto DiagnoseBadNumberOfBindings = [&]() -> bool { | |||
1315 | unsigned NumFields = | |||
1316 | std::count_if(RD->field_begin(), RD->field_end(), | |||
1317 | [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); | |||
1318 | assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0) : __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1318, __PRETTY_FUNCTION__)); | |||
1319 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | |||
1320 | << DecompType << (unsigned)Bindings.size() << NumFields | |||
1321 | << (NumFields < Bindings.size()); | |||
1322 | return true; | |||
1323 | }; | |||
1324 | ||||
1325 | // all of E's non-static data members shall be [...] well-formed | |||
1326 | // when named as e.name in the context of the structured binding, | |||
1327 | // E shall not have an anonymous union member, ... | |||
1328 | unsigned I = 0; | |||
1329 | for (auto *FD : RD->fields()) { | |||
1330 | if (FD->isUnnamedBitfield()) | |||
1331 | continue; | |||
1332 | ||||
1333 | if (FD->isAnonymousStructOrUnion()) { | |||
1334 | S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) | |||
1335 | << DecompType << FD->getType()->isUnionType(); | |||
1336 | S.Diag(FD->getLocation(), diag::note_declared_at); | |||
1337 | return true; | |||
1338 | } | |||
1339 | ||||
1340 | // We have a real field to bind. | |||
1341 | if (I >= Bindings.size()) | |||
1342 | return DiagnoseBadNumberOfBindings(); | |||
1343 | auto *B = Bindings[I++]; | |||
1344 | SourceLocation Loc = B->getLocation(); | |||
1345 | ||||
1346 | // The field must be accessible in the context of the structured binding. | |||
1347 | // We already checked that the base class is accessible. | |||
1348 | // FIXME: Add 'const' to AccessedEntity's classes so we can remove the | |||
1349 | // const_cast here. | |||
1350 | S.CheckStructuredBindingMemberAccess( | |||
1351 | Loc, const_cast<CXXRecordDecl *>(OrigRD), | |||
1352 | DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( | |||
1353 | BasePair.getAccess(), FD->getAccess()))); | |||
1354 | ||||
1355 | // Initialize the binding to Src.FD. | |||
1356 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | |||
1357 | if (E.isInvalid()) | |||
1358 | return true; | |||
1359 | E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, | |||
1360 | VK_LValue, &BasePath); | |||
1361 | if (E.isInvalid()) | |||
1362 | return true; | |||
1363 | E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, | |||
1364 | CXXScopeSpec(), FD, | |||
1365 | DeclAccessPair::make(FD, FD->getAccess()), | |||
1366 | DeclarationNameInfo(FD->getDeclName(), Loc)); | |||
1367 | if (E.isInvalid()) | |||
1368 | return true; | |||
1369 | ||||
1370 | // If the type of the member is T, the referenced type is cv T, where cv is | |||
1371 | // the cv-qualification of the decomposition expression. | |||
1372 | // | |||
1373 | // FIXME: We resolve a defect here: if the field is mutable, we do not add | |||
1374 | // 'const' to the type of the field. | |||
1375 | Qualifiers Q = DecompType.getQualifiers(); | |||
1376 | if (FD->isMutable()) | |||
1377 | Q.removeConst(); | |||
1378 | B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); | |||
1379 | } | |||
1380 | ||||
1381 | if (I != Bindings.size()) | |||
1382 | return DiagnoseBadNumberOfBindings(); | |||
1383 | ||||
1384 | return false; | |||
1385 | } | |||
1386 | ||||
1387 | void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { | |||
1388 | QualType DecompType = DD->getType(); | |||
1389 | ||||
1390 | // If the type of the decomposition is dependent, then so is the type of | |||
1391 | // each binding. | |||
1392 | if (DecompType->isDependentType()) { | |||
1393 | for (auto *B : DD->bindings()) | |||
1394 | B->setType(Context.DependentTy); | |||
1395 | return; | |||
1396 | } | |||
1397 | ||||
1398 | DecompType = DecompType.getNonReferenceType(); | |||
1399 | ArrayRef<BindingDecl*> Bindings = DD->bindings(); | |||
1400 | ||||
1401 | // C++1z [dcl.decomp]/2: | |||
1402 | // If E is an array type [...] | |||
1403 | // As an extension, we also support decomposition of built-in complex and | |||
1404 | // vector types. | |||
1405 | if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { | |||
1406 | if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) | |||
1407 | DD->setInvalidDecl(); | |||
1408 | return; | |||
1409 | } | |||
1410 | if (auto *VT = DecompType->getAs<VectorType>()) { | |||
1411 | if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) | |||
1412 | DD->setInvalidDecl(); | |||
1413 | return; | |||
1414 | } | |||
1415 | if (auto *CT = DecompType->getAs<ComplexType>()) { | |||
1416 | if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) | |||
1417 | DD->setInvalidDecl(); | |||
1418 | return; | |||
1419 | } | |||
1420 | ||||
1421 | // C++1z [dcl.decomp]/3: | |||
1422 | // if the expression std::tuple_size<E>::value is a well-formed integral | |||
1423 | // constant expression, [...] | |||
1424 | llvm::APSInt TupleSize(32); | |||
1425 | switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { | |||
1426 | case IsTupleLike::Error: | |||
1427 | DD->setInvalidDecl(); | |||
1428 | return; | |||
1429 | ||||
1430 | case IsTupleLike::TupleLike: | |||
1431 | if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) | |||
1432 | DD->setInvalidDecl(); | |||
1433 | return; | |||
1434 | ||||
1435 | case IsTupleLike::NotTupleLike: | |||
1436 | break; | |||
1437 | } | |||
1438 | ||||
1439 | // C++1z [dcl.dcl]/8: | |||
1440 | // [E shall be of array or non-union class type] | |||
1441 | CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); | |||
1442 | if (!RD || RD->isUnion()) { | |||
1443 | Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) | |||
1444 | << DD << !RD << DecompType; | |||
1445 | DD->setInvalidDecl(); | |||
1446 | return; | |||
1447 | } | |||
1448 | ||||
1449 | // C++1z [dcl.decomp]/4: | |||
1450 | // all of E's non-static data members shall be [...] direct members of | |||
1451 | // E or of the same unambiguous public base class of E, ... | |||
1452 | if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) | |||
1453 | DD->setInvalidDecl(); | |||
1454 | } | |||
1455 | ||||
1456 | /// Merge the exception specifications of two variable declarations. | |||
1457 | /// | |||
1458 | /// This is called when there's a redeclaration of a VarDecl. The function | |||
1459 | /// checks if the redeclaration might have an exception specification and | |||
1460 | /// validates compatibility and merges the specs if necessary. | |||
1461 | void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { | |||
1462 | // Shortcut if exceptions are disabled. | |||
1463 | if (!getLangOpts().CXXExceptions) | |||
1464 | return; | |||
1465 | ||||
1466 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1467, __PRETTY_FUNCTION__)) | |||
1467 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1467, __PRETTY_FUNCTION__)); | |||
1468 | ||||
1469 | QualType NewType = New->getType(); | |||
1470 | QualType OldType = Old->getType(); | |||
1471 | ||||
1472 | // We're only interested in pointers and references to functions, as well | |||
1473 | // as pointers to member functions. | |||
1474 | if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { | |||
1475 | NewType = R->getPointeeType(); | |||
1476 | OldType = OldType->getAs<ReferenceType>()->getPointeeType(); | |||
1477 | } else if (const PointerType *P = NewType->getAs<PointerType>()) { | |||
1478 | NewType = P->getPointeeType(); | |||
1479 | OldType = OldType->getAs<PointerType>()->getPointeeType(); | |||
1480 | } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { | |||
1481 | NewType = M->getPointeeType(); | |||
1482 | OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); | |||
1483 | } | |||
1484 | ||||
1485 | if (!NewType->isFunctionProtoType()) | |||
1486 | return; | |||
1487 | ||||
1488 | // There's lots of special cases for functions. For function pointers, system | |||
1489 | // libraries are hopefully not as broken so that we don't need these | |||
1490 | // workarounds. | |||
1491 | if (CheckEquivalentExceptionSpec( | |||
1492 | OldType->getAs<FunctionProtoType>(), Old->getLocation(), | |||
1493 | NewType->getAs<FunctionProtoType>(), New->getLocation())) { | |||
1494 | New->setInvalidDecl(); | |||
1495 | } | |||
1496 | } | |||
1497 | ||||
1498 | /// CheckCXXDefaultArguments - Verify that the default arguments for a | |||
1499 | /// function declaration are well-formed according to C++ | |||
1500 | /// [dcl.fct.default]. | |||
1501 | void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { | |||
1502 | unsigned NumParams = FD->getNumParams(); | |||
1503 | unsigned p; | |||
1504 | ||||
1505 | // Find first parameter with a default argument | |||
1506 | for (p = 0; p < NumParams; ++p) { | |||
1507 | ParmVarDecl *Param = FD->getParamDecl(p); | |||
1508 | if (Param->hasDefaultArg()) | |||
1509 | break; | |||
1510 | } | |||
1511 | ||||
1512 | // C++11 [dcl.fct.default]p4: | |||
1513 | // In a given function declaration, each parameter subsequent to a parameter | |||
1514 | // with a default argument shall have a default argument supplied in this or | |||
1515 | // a previous declaration or shall be a function parameter pack. A default | |||
1516 | // argument shall not be redefined by a later declaration (not even to the | |||
1517 | // same value). | |||
1518 | unsigned LastMissingDefaultArg = 0; | |||
1519 | for (; p < NumParams; ++p) { | |||
1520 | ParmVarDecl *Param = FD->getParamDecl(p); | |||
1521 | if (!Param->hasDefaultArg() && !Param->isParameterPack()) { | |||
1522 | if (Param->isInvalidDecl()) | |||
1523 | /* We already complained about this parameter. */; | |||
1524 | else if (Param->getIdentifier()) | |||
1525 | Diag(Param->getLocation(), | |||
1526 | diag::err_param_default_argument_missing_name) | |||
1527 | << Param->getIdentifier(); | |||
1528 | else | |||
1529 | Diag(Param->getLocation(), | |||
1530 | diag::err_param_default_argument_missing); | |||
1531 | ||||
1532 | LastMissingDefaultArg = p; | |||
1533 | } | |||
1534 | } | |||
1535 | ||||
1536 | if (LastMissingDefaultArg > 0) { | |||
1537 | // Some default arguments were missing. Clear out all of the | |||
1538 | // default arguments up to (and including) the last missing | |||
1539 | // default argument, so that we leave the function parameters | |||
1540 | // in a semantically valid state. | |||
1541 | for (p = 0; p <= LastMissingDefaultArg; ++p) { | |||
1542 | ParmVarDecl *Param = FD->getParamDecl(p); | |||
1543 | if (Param->hasDefaultArg()) { | |||
1544 | Param->setDefaultArg(nullptr); | |||
1545 | } | |||
1546 | } | |||
1547 | } | |||
1548 | } | |||
1549 | ||||
1550 | // CheckConstexprParameterTypes - Check whether a function's parameter types | |||
1551 | // are all literal types. If so, return true. If not, produce a suitable | |||
1552 | // diagnostic and return false. | |||
1553 | static bool CheckConstexprParameterTypes(Sema &SemaRef, | |||
1554 | const FunctionDecl *FD) { | |||
1555 | unsigned ArgIndex = 0; | |||
1556 | const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); | |||
1557 | for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), | |||
1558 | e = FT->param_type_end(); | |||
1559 | i != e; ++i, ++ArgIndex) { | |||
1560 | const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); | |||
1561 | SourceLocation ParamLoc = PD->getLocation(); | |||
1562 | if (!(*i)->isDependentType() && | |||
1563 | SemaRef.RequireLiteralType(ParamLoc, *i, | |||
1564 | diag::err_constexpr_non_literal_param, | |||
1565 | ArgIndex+1, PD->getSourceRange(), | |||
1566 | isa<CXXConstructorDecl>(FD))) | |||
1567 | return false; | |||
1568 | } | |||
1569 | return true; | |||
1570 | } | |||
1571 | ||||
1572 | /// Get diagnostic %select index for tag kind for | |||
1573 | /// record diagnostic message. | |||
1574 | /// WARNING: Indexes apply to particular diagnostics only! | |||
1575 | /// | |||
1576 | /// \returns diagnostic %select index. | |||
1577 | static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { | |||
1578 | switch (Tag) { | |||
1579 | case TTK_Struct: return 0; | |||
1580 | case TTK_Interface: return 1; | |||
1581 | case TTK_Class: return 2; | |||
1582 | default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1582); | |||
1583 | } | |||
1584 | } | |||
1585 | ||||
1586 | // CheckConstexprFunctionDecl - Check whether a function declaration satisfies | |||
1587 | // the requirements of a constexpr function definition or a constexpr | |||
1588 | // constructor definition. If so, return true. If not, produce appropriate | |||
1589 | // diagnostics and return false. | |||
1590 | // | |||
1591 | // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. | |||
1592 | bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { | |||
1593 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
1594 | if (MD && MD->isInstance()) { | |||
1595 | // C++11 [dcl.constexpr]p4: | |||
1596 | // The definition of a constexpr constructor shall satisfy the following | |||
1597 | // constraints: | |||
1598 | // - the class shall not have any virtual base classes; | |||
1599 | const CXXRecordDecl *RD = MD->getParent(); | |||
1600 | if (RD->getNumVBases()) { | |||
1601 | Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) | |||
1602 | << isa<CXXConstructorDecl>(NewFD) | |||
1603 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | |||
1604 | for (const auto &I : RD->vbases()) | |||
1605 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) | |||
1606 | << I.getSourceRange(); | |||
1607 | return false; | |||
1608 | } | |||
1609 | } | |||
1610 | ||||
1611 | if (!isa<CXXConstructorDecl>(NewFD)) { | |||
1612 | // C++11 [dcl.constexpr]p3: | |||
1613 | // The definition of a constexpr function shall satisfy the following | |||
1614 | // constraints: | |||
1615 | // - it shall not be virtual; | |||
1616 | const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); | |||
1617 | if (Method && Method->isVirtual()) { | |||
1618 | Method = Method->getCanonicalDecl(); | |||
1619 | Diag(Method->getLocation(), diag::err_constexpr_virtual); | |||
1620 | ||||
1621 | // If it's not obvious why this function is virtual, find an overridden | |||
1622 | // function which uses the 'virtual' keyword. | |||
1623 | const CXXMethodDecl *WrittenVirtual = Method; | |||
1624 | while (!WrittenVirtual->isVirtualAsWritten()) | |||
1625 | WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); | |||
1626 | if (WrittenVirtual != Method) | |||
1627 | Diag(WrittenVirtual->getLocation(), | |||
1628 | diag::note_overridden_virtual_function); | |||
1629 | return false; | |||
1630 | } | |||
1631 | ||||
1632 | // - its return type shall be a literal type; | |||
1633 | QualType RT = NewFD->getReturnType(); | |||
1634 | if (!RT->isDependentType() && | |||
1635 | RequireLiteralType(NewFD->getLocation(), RT, | |||
1636 | diag::err_constexpr_non_literal_return)) | |||
1637 | return false; | |||
1638 | } | |||
1639 | ||||
1640 | // - each of its parameter types shall be a literal type; | |||
1641 | if (!CheckConstexprParameterTypes(*this, NewFD)) | |||
1642 | return false; | |||
1643 | ||||
1644 | return true; | |||
1645 | } | |||
1646 | ||||
1647 | /// Check the given declaration statement is legal within a constexpr function | |||
1648 | /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. | |||
1649 | /// | |||
1650 | /// \return true if the body is OK (maybe only as an extension), false if we | |||
1651 | /// have diagnosed a problem. | |||
1652 | static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, | |||
1653 | DeclStmt *DS, SourceLocation &Cxx1yLoc) { | |||
1654 | // C++11 [dcl.constexpr]p3 and p4: | |||
1655 | // The definition of a constexpr function(p3) or constructor(p4) [...] shall | |||
1656 | // contain only | |||
1657 | for (const auto *DclIt : DS->decls()) { | |||
1658 | switch (DclIt->getKind()) { | |||
1659 | case Decl::StaticAssert: | |||
1660 | case Decl::Using: | |||
1661 | case Decl::UsingShadow: | |||
1662 | case Decl::UsingDirective: | |||
1663 | case Decl::UnresolvedUsingTypename: | |||
1664 | case Decl::UnresolvedUsingValue: | |||
1665 | // - static_assert-declarations | |||
1666 | // - using-declarations, | |||
1667 | // - using-directives, | |||
1668 | continue; | |||
1669 | ||||
1670 | case Decl::Typedef: | |||
1671 | case Decl::TypeAlias: { | |||
1672 | // - typedef declarations and alias-declarations that do not define | |||
1673 | // classes or enumerations, | |||
1674 | const auto *TN = cast<TypedefNameDecl>(DclIt); | |||
1675 | if (TN->getUnderlyingType()->isVariablyModifiedType()) { | |||
1676 | // Don't allow variably-modified types in constexpr functions. | |||
1677 | TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); | |||
1678 | SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) | |||
1679 | << TL.getSourceRange() << TL.getType() | |||
1680 | << isa<CXXConstructorDecl>(Dcl); | |||
1681 | return false; | |||
1682 | } | |||
1683 | continue; | |||
1684 | } | |||
1685 | ||||
1686 | case Decl::Enum: | |||
1687 | case Decl::CXXRecord: | |||
1688 | // C++1y allows types to be defined, not just declared. | |||
1689 | if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) | |||
1690 | SemaRef.Diag(DS->getBeginLoc(), | |||
1691 | SemaRef.getLangOpts().CPlusPlus14 | |||
1692 | ? diag::warn_cxx11_compat_constexpr_type_definition | |||
1693 | : diag::ext_constexpr_type_definition) | |||
1694 | << isa<CXXConstructorDecl>(Dcl); | |||
1695 | continue; | |||
1696 | ||||
1697 | case Decl::EnumConstant: | |||
1698 | case Decl::IndirectField: | |||
1699 | case Decl::ParmVar: | |||
1700 | // These can only appear with other declarations which are banned in | |||
1701 | // C++11 and permitted in C++1y, so ignore them. | |||
1702 | continue; | |||
1703 | ||||
1704 | case Decl::Var: | |||
1705 | case Decl::Decomposition: { | |||
1706 | // C++1y [dcl.constexpr]p3 allows anything except: | |||
1707 | // a definition of a variable of non-literal type or of static or | |||
1708 | // thread storage duration or for which no initialization is performed. | |||
1709 | const auto *VD = cast<VarDecl>(DclIt); | |||
1710 | if (VD->isThisDeclarationADefinition()) { | |||
1711 | if (VD->isStaticLocal()) { | |||
1712 | SemaRef.Diag(VD->getLocation(), | |||
1713 | diag::err_constexpr_local_var_static) | |||
1714 | << isa<CXXConstructorDecl>(Dcl) | |||
1715 | << (VD->getTLSKind() == VarDecl::TLS_Dynamic); | |||
1716 | return false; | |||
1717 | } | |||
1718 | if (!VD->getType()->isDependentType() && | |||
1719 | SemaRef.RequireLiteralType( | |||
1720 | VD->getLocation(), VD->getType(), | |||
1721 | diag::err_constexpr_local_var_non_literal_type, | |||
1722 | isa<CXXConstructorDecl>(Dcl))) | |||
1723 | return false; | |||
1724 | if (!VD->getType()->isDependentType() && | |||
1725 | !VD->hasInit() && !VD->isCXXForRangeDecl()) { | |||
1726 | SemaRef.Diag(VD->getLocation(), | |||
1727 | diag::err_constexpr_local_var_no_init) | |||
1728 | << isa<CXXConstructorDecl>(Dcl); | |||
1729 | return false; | |||
1730 | } | |||
1731 | } | |||
1732 | SemaRef.Diag(VD->getLocation(), | |||
1733 | SemaRef.getLangOpts().CPlusPlus14 | |||
1734 | ? diag::warn_cxx11_compat_constexpr_local_var | |||
1735 | : diag::ext_constexpr_local_var) | |||
1736 | << isa<CXXConstructorDecl>(Dcl); | |||
1737 | continue; | |||
1738 | } | |||
1739 | ||||
1740 | case Decl::NamespaceAlias: | |||
1741 | case Decl::Function: | |||
1742 | // These are disallowed in C++11 and permitted in C++1y. Allow them | |||
1743 | // everywhere as an extension. | |||
1744 | if (!Cxx1yLoc.isValid()) | |||
1745 | Cxx1yLoc = DS->getBeginLoc(); | |||
1746 | continue; | |||
1747 | ||||
1748 | default: | |||
1749 | SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) | |||
1750 | << isa<CXXConstructorDecl>(Dcl); | |||
1751 | return false; | |||
1752 | } | |||
1753 | } | |||
1754 | ||||
1755 | return true; | |||
1756 | } | |||
1757 | ||||
1758 | /// Check that the given field is initialized within a constexpr constructor. | |||
1759 | /// | |||
1760 | /// \param Dcl The constexpr constructor being checked. | |||
1761 | /// \param Field The field being checked. This may be a member of an anonymous | |||
1762 | /// struct or union nested within the class being checked. | |||
1763 | /// \param Inits All declarations, including anonymous struct/union members and | |||
1764 | /// indirect members, for which any initialization was provided. | |||
1765 | /// \param Diagnosed Set to true if an error is produced. | |||
1766 | static void CheckConstexprCtorInitializer(Sema &SemaRef, | |||
1767 | const FunctionDecl *Dcl, | |||
1768 | FieldDecl *Field, | |||
1769 | llvm::SmallSet<Decl*, 16> &Inits, | |||
1770 | bool &Diagnosed) { | |||
1771 | if (Field->isInvalidDecl()) | |||
1772 | return; | |||
1773 | ||||
1774 | if (Field->isUnnamedBitfield()) | |||
1775 | return; | |||
1776 | ||||
1777 | // Anonymous unions with no variant members and empty anonymous structs do not | |||
1778 | // need to be explicitly initialized. FIXME: Anonymous structs that contain no | |||
1779 | // indirect fields don't need initializing. | |||
1780 | if (Field->isAnonymousStructOrUnion() && | |||
1781 | (Field->getType()->isUnionType() | |||
1782 | ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() | |||
1783 | : Field->getType()->getAsCXXRecordDecl()->isEmpty())) | |||
1784 | return; | |||
1785 | ||||
1786 | if (!Inits.count(Field)) { | |||
1787 | if (!Diagnosed) { | |||
1788 | SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); | |||
1789 | Diagnosed = true; | |||
1790 | } | |||
1791 | SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); | |||
1792 | } else if (Field->isAnonymousStructOrUnion()) { | |||
1793 | const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); | |||
1794 | for (auto *I : RD->fields()) | |||
1795 | // If an anonymous union contains an anonymous struct of which any member | |||
1796 | // is initialized, all members must be initialized. | |||
1797 | if (!RD->isUnion() || Inits.count(I)) | |||
1798 | CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); | |||
1799 | } | |||
1800 | } | |||
1801 | ||||
1802 | /// Check the provided statement is allowed in a constexpr function | |||
1803 | /// definition. | |||
1804 | static bool | |||
1805 | CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, | |||
1806 | SmallVectorImpl<SourceLocation> &ReturnStmts, | |||
1807 | SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) { | |||
1808 | // - its function-body shall be [...] a compound-statement that contains only | |||
1809 | switch (S->getStmtClass()) { | |||
1810 | case Stmt::NullStmtClass: | |||
1811 | // - null statements, | |||
1812 | return true; | |||
1813 | ||||
1814 | case Stmt::DeclStmtClass: | |||
1815 | // - static_assert-declarations | |||
1816 | // - using-declarations, | |||
1817 | // - using-directives, | |||
1818 | // - typedef declarations and alias-declarations that do not define | |||
1819 | // classes or enumerations, | |||
1820 | if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) | |||
1821 | return false; | |||
1822 | return true; | |||
1823 | ||||
1824 | case Stmt::ReturnStmtClass: | |||
1825 | // - and exactly one return statement; | |||
1826 | if (isa<CXXConstructorDecl>(Dcl)) { | |||
1827 | // C++1y allows return statements in constexpr constructors. | |||
1828 | if (!Cxx1yLoc.isValid()) | |||
1829 | Cxx1yLoc = S->getBeginLoc(); | |||
1830 | return true; | |||
1831 | } | |||
1832 | ||||
1833 | ReturnStmts.push_back(S->getBeginLoc()); | |||
1834 | return true; | |||
1835 | ||||
1836 | case Stmt::CompoundStmtClass: { | |||
1837 | // C++1y allows compound-statements. | |||
1838 | if (!Cxx1yLoc.isValid()) | |||
1839 | Cxx1yLoc = S->getBeginLoc(); | |||
1840 | ||||
1841 | CompoundStmt *CompStmt = cast<CompoundStmt>(S); | |||
1842 | for (auto *BodyIt : CompStmt->body()) { | |||
1843 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, | |||
1844 | Cxx1yLoc, Cxx2aLoc)) | |||
1845 | return false; | |||
1846 | } | |||
1847 | return true; | |||
1848 | } | |||
1849 | ||||
1850 | case Stmt::AttributedStmtClass: | |||
1851 | if (!Cxx1yLoc.isValid()) | |||
1852 | Cxx1yLoc = S->getBeginLoc(); | |||
1853 | return true; | |||
1854 | ||||
1855 | case Stmt::IfStmtClass: { | |||
1856 | // C++1y allows if-statements. | |||
1857 | if (!Cxx1yLoc.isValid()) | |||
1858 | Cxx1yLoc = S->getBeginLoc(); | |||
1859 | ||||
1860 | IfStmt *If = cast<IfStmt>(S); | |||
1861 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, | |||
1862 | Cxx1yLoc, Cxx2aLoc)) | |||
1863 | return false; | |||
1864 | if (If->getElse() && | |||
1865 | !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, | |||
1866 | Cxx1yLoc, Cxx2aLoc)) | |||
1867 | return false; | |||
1868 | return true; | |||
1869 | } | |||
1870 | ||||
1871 | case Stmt::WhileStmtClass: | |||
1872 | case Stmt::DoStmtClass: | |||
1873 | case Stmt::ForStmtClass: | |||
1874 | case Stmt::CXXForRangeStmtClass: | |||
1875 | case Stmt::ContinueStmtClass: | |||
1876 | // C++1y allows all of these. We don't allow them as extensions in C++11, | |||
1877 | // because they don't make sense without variable mutation. | |||
1878 | if (!SemaRef.getLangOpts().CPlusPlus14) | |||
1879 | break; | |||
1880 | if (!Cxx1yLoc.isValid()) | |||
1881 | Cxx1yLoc = S->getBeginLoc(); | |||
1882 | for (Stmt *SubStmt : S->children()) | |||
1883 | if (SubStmt && | |||
1884 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | |||
1885 | Cxx1yLoc, Cxx2aLoc)) | |||
1886 | return false; | |||
1887 | return true; | |||
1888 | ||||
1889 | case Stmt::SwitchStmtClass: | |||
1890 | case Stmt::CaseStmtClass: | |||
1891 | case Stmt::DefaultStmtClass: | |||
1892 | case Stmt::BreakStmtClass: | |||
1893 | // C++1y allows switch-statements, and since they don't need variable | |||
1894 | // mutation, we can reasonably allow them in C++11 as an extension. | |||
1895 | if (!Cxx1yLoc.isValid()) | |||
1896 | Cxx1yLoc = S->getBeginLoc(); | |||
1897 | for (Stmt *SubStmt : S->children()) | |||
1898 | if (SubStmt && | |||
1899 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | |||
1900 | Cxx1yLoc, Cxx2aLoc)) | |||
1901 | return false; | |||
1902 | return true; | |||
1903 | ||||
1904 | case Stmt::CXXTryStmtClass: | |||
1905 | if (Cxx2aLoc.isInvalid()) | |||
1906 | Cxx2aLoc = S->getBeginLoc(); | |||
1907 | for (Stmt *SubStmt : S->children()) { | |||
1908 | if (SubStmt && | |||
1909 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | |||
1910 | Cxx1yLoc, Cxx2aLoc)) | |||
1911 | return false; | |||
1912 | } | |||
1913 | return true; | |||
1914 | ||||
1915 | case Stmt::CXXCatchStmtClass: | |||
1916 | // Do not bother checking the language mode (already covered by the | |||
1917 | // try block check). | |||
1918 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, | |||
1919 | cast<CXXCatchStmt>(S)->getHandlerBlock(), | |||
1920 | ReturnStmts, Cxx1yLoc, Cxx2aLoc)) | |||
1921 | return false; | |||
1922 | return true; | |||
1923 | ||||
1924 | default: | |||
1925 | if (!isa<Expr>(S)) | |||
1926 | break; | |||
1927 | ||||
1928 | // C++1y allows expression-statements. | |||
1929 | if (!Cxx1yLoc.isValid()) | |||
1930 | Cxx1yLoc = S->getBeginLoc(); | |||
1931 | return true; | |||
1932 | } | |||
1933 | ||||
1934 | SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) | |||
1935 | << isa<CXXConstructorDecl>(Dcl); | |||
1936 | return false; | |||
1937 | } | |||
1938 | ||||
1939 | /// Check the body for the given constexpr function declaration only contains | |||
1940 | /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. | |||
1941 | /// | |||
1942 | /// \return true if the body is OK, false if we have diagnosed a problem. | |||
1943 | bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { | |||
1944 | SmallVector<SourceLocation, 4> ReturnStmts; | |||
1945 | ||||
1946 | if (isa<CXXTryStmt>(Body)) { | |||
1947 | // C++11 [dcl.constexpr]p3: | |||
1948 | // The definition of a constexpr function shall satisfy the following | |||
1949 | // constraints: [...] | |||
1950 | // - its function-body shall be = delete, = default, or a | |||
1951 | // compound-statement | |||
1952 | // | |||
1953 | // C++11 [dcl.constexpr]p4: | |||
1954 | // In the definition of a constexpr constructor, [...] | |||
1955 | // - its function-body shall not be a function-try-block; | |||
1956 | // | |||
1957 | // This restriction is lifted in C++2a, as long as inner statements also | |||
1958 | // apply the general constexpr rules. | |||
1959 | Diag(Body->getBeginLoc(), | |||
1960 | !getLangOpts().CPlusPlus2a | |||
1961 | ? diag::ext_constexpr_function_try_block_cxx2a | |||
1962 | : diag::warn_cxx17_compat_constexpr_function_try_block) | |||
1963 | << isa<CXXConstructorDecl>(Dcl); | |||
1964 | } | |||
1965 | ||||
1966 | // - its function-body shall be [...] a compound-statement that contains only | |||
1967 | // [... list of cases ...] | |||
1968 | // | |||
1969 | // Note that walking the children here is enough to properly check for | |||
1970 | // CompoundStmt and CXXTryStmt body. | |||
1971 | SourceLocation Cxx1yLoc, Cxx2aLoc; | |||
1972 | for (Stmt *SubStmt : Body->children()) { | |||
1973 | if (SubStmt && | |||
1974 | !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts, | |||
1975 | Cxx1yLoc, Cxx2aLoc)) | |||
1976 | return false; | |||
1977 | } | |||
1978 | ||||
1979 | if (Cxx2aLoc.isValid()) | |||
1980 | Diag(Cxx2aLoc, | |||
1981 | getLangOpts().CPlusPlus2a | |||
1982 | ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt | |||
1983 | : diag::ext_constexpr_body_invalid_stmt_cxx2a) | |||
1984 | << isa<CXXConstructorDecl>(Dcl); | |||
1985 | if (Cxx1yLoc.isValid()) | |||
1986 | Diag(Cxx1yLoc, | |||
1987 | getLangOpts().CPlusPlus14 | |||
1988 | ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt | |||
1989 | : diag::ext_constexpr_body_invalid_stmt) | |||
1990 | << isa<CXXConstructorDecl>(Dcl); | |||
1991 | ||||
1992 | if (const CXXConstructorDecl *Constructor | |||
1993 | = dyn_cast<CXXConstructorDecl>(Dcl)) { | |||
1994 | const CXXRecordDecl *RD = Constructor->getParent(); | |||
1995 | // DR1359: | |||
1996 | // - every non-variant non-static data member and base class sub-object | |||
1997 | // shall be initialized; | |||
1998 | // DR1460: | |||
1999 | // - if the class is a union having variant members, exactly one of them | |||
2000 | // shall be initialized; | |||
2001 | if (RD->isUnion()) { | |||
2002 | if (Constructor->getNumCtorInitializers() == 0 && | |||
2003 | RD->hasVariantMembers()) { | |||
2004 | Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); | |||
2005 | return false; | |||
2006 | } | |||
2007 | } else if (!Constructor->isDependentContext() && | |||
2008 | !Constructor->isDelegatingConstructor()) { | |||
2009 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2009, __PRETTY_FUNCTION__)); | |||
2010 | ||||
2011 | // Skip detailed checking if we have enough initializers, and we would | |||
2012 | // allow at most one initializer per member. | |||
2013 | bool AnyAnonStructUnionMembers = false; | |||
2014 | unsigned Fields = 0; | |||
2015 | for (CXXRecordDecl::field_iterator I = RD->field_begin(), | |||
2016 | E = RD->field_end(); I != E; ++I, ++Fields) { | |||
2017 | if (I->isAnonymousStructOrUnion()) { | |||
2018 | AnyAnonStructUnionMembers = true; | |||
2019 | break; | |||
2020 | } | |||
2021 | } | |||
2022 | // DR1460: | |||
2023 | // - if the class is a union-like class, but is not a union, for each of | |||
2024 | // its anonymous union members having variant members, exactly one of | |||
2025 | // them shall be initialized; | |||
2026 | if (AnyAnonStructUnionMembers || | |||
2027 | Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { | |||
2028 | // Check initialization of non-static data members. Base classes are | |||
2029 | // always initialized so do not need to be checked. Dependent bases | |||
2030 | // might not have initializers in the member initializer list. | |||
2031 | llvm::SmallSet<Decl*, 16> Inits; | |||
2032 | for (const auto *I: Constructor->inits()) { | |||
2033 | if (FieldDecl *FD = I->getMember()) | |||
2034 | Inits.insert(FD); | |||
2035 | else if (IndirectFieldDecl *ID = I->getIndirectMember()) | |||
2036 | Inits.insert(ID->chain_begin(), ID->chain_end()); | |||
2037 | } | |||
2038 | ||||
2039 | bool Diagnosed = false; | |||
2040 | for (auto *I : RD->fields()) | |||
2041 | CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); | |||
2042 | if (Diagnosed) | |||
2043 | return false; | |||
2044 | } | |||
2045 | } | |||
2046 | } else { | |||
2047 | if (ReturnStmts.empty()) { | |||
2048 | // C++1y doesn't require constexpr functions to contain a 'return' | |||
2049 | // statement. We still do, unless the return type might be void, because | |||
2050 | // otherwise if there's no return statement, the function cannot | |||
2051 | // be used in a core constant expression. | |||
2052 | bool OK = getLangOpts().CPlusPlus14 && | |||
2053 | (Dcl->getReturnType()->isVoidType() || | |||
2054 | Dcl->getReturnType()->isDependentType()); | |||
2055 | Diag(Dcl->getLocation(), | |||
2056 | OK ? diag::warn_cxx11_compat_constexpr_body_no_return | |||
2057 | : diag::err_constexpr_body_no_return); | |||
2058 | if (!OK) | |||
2059 | return false; | |||
2060 | } else if (ReturnStmts.size() > 1) { | |||
2061 | Diag(ReturnStmts.back(), | |||
2062 | getLangOpts().CPlusPlus14 | |||
2063 | ? diag::warn_cxx11_compat_constexpr_body_multiple_return | |||
2064 | : diag::ext_constexpr_body_multiple_return); | |||
2065 | for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) | |||
2066 | Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); | |||
2067 | } | |||
2068 | } | |||
2069 | ||||
2070 | // C++11 [dcl.constexpr]p5: | |||
2071 | // if no function argument values exist such that the function invocation | |||
2072 | // substitution would produce a constant expression, the program is | |||
2073 | // ill-formed; no diagnostic required. | |||
2074 | // C++11 [dcl.constexpr]p3: | |||
2075 | // - every constructor call and implicit conversion used in initializing the | |||
2076 | // return value shall be one of those allowed in a constant expression. | |||
2077 | // C++11 [dcl.constexpr]p4: | |||
2078 | // - every constructor involved in initializing non-static data members and | |||
2079 | // base class sub-objects shall be a constexpr constructor. | |||
2080 | SmallVector<PartialDiagnosticAt, 8> Diags; | |||
2081 | if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { | |||
2082 | Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) | |||
2083 | << isa<CXXConstructorDecl>(Dcl); | |||
2084 | for (size_t I = 0, N = Diags.size(); I != N; ++I) | |||
2085 | Diag(Diags[I].first, Diags[I].second); | |||
2086 | // Don't return false here: we allow this for compatibility in | |||
2087 | // system headers. | |||
2088 | } | |||
2089 | ||||
2090 | return true; | |||
2091 | } | |||
2092 | ||||
2093 | /// Get the class that is directly named by the current context. This is the | |||
2094 | /// class for which an unqualified-id in this scope could name a constructor | |||
2095 | /// or destructor. | |||
2096 | /// | |||
2097 | /// If the scope specifier denotes a class, this will be that class. | |||
2098 | /// If the scope specifier is empty, this will be the class whose | |||
2099 | /// member-specification we are currently within. Otherwise, there | |||
2100 | /// is no such class. | |||
2101 | CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { | |||
2102 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2102, __PRETTY_FUNCTION__)); | |||
2103 | ||||
2104 | if (SS && SS->isInvalid()) | |||
2105 | return nullptr; | |||
2106 | ||||
2107 | if (SS && SS->isNotEmpty()) { | |||
2108 | DeclContext *DC = computeDeclContext(*SS, true); | |||
2109 | return dyn_cast_or_null<CXXRecordDecl>(DC); | |||
2110 | } | |||
2111 | ||||
2112 | return dyn_cast_or_null<CXXRecordDecl>(CurContext); | |||
2113 | } | |||
2114 | ||||
2115 | /// isCurrentClassName - Determine whether the identifier II is the | |||
2116 | /// name of the class type currently being defined. In the case of | |||
2117 | /// nested classes, this will only return true if II is the name of | |||
2118 | /// the innermost class. | |||
2119 | bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, | |||
2120 | const CXXScopeSpec *SS) { | |||
2121 | CXXRecordDecl *CurDecl = getCurrentClass(S, SS); | |||
2122 | return CurDecl && &II == CurDecl->getIdentifier(); | |||
2123 | } | |||
2124 | ||||
2125 | /// Determine whether the identifier II is a typo for the name of | |||
2126 | /// the class type currently being defined. If so, update it to the identifier | |||
2127 | /// that should have been used. | |||
2128 | bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { | |||
2129 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2129, __PRETTY_FUNCTION__)); | |||
2130 | ||||
2131 | if (!getLangOpts().SpellChecking) | |||
2132 | return false; | |||
2133 | ||||
2134 | CXXRecordDecl *CurDecl; | |||
2135 | if (SS && SS->isSet() && !SS->isInvalid()) { | |||
2136 | DeclContext *DC = computeDeclContext(*SS, true); | |||
2137 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); | |||
2138 | } else | |||
2139 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); | |||
2140 | ||||
2141 | if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && | |||
2142 | 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) | |||
2143 | < II->getLength()) { | |||
2144 | II = CurDecl->getIdentifier(); | |||
2145 | return true; | |||
2146 | } | |||
2147 | ||||
2148 | return false; | |||
2149 | } | |||
2150 | ||||
2151 | /// Determine whether the given class is a base class of the given | |||
2152 | /// class, including looking at dependent bases. | |||
2153 | static bool findCircularInheritance(const CXXRecordDecl *Class, | |||
2154 | const CXXRecordDecl *Current) { | |||
2155 | SmallVector<const CXXRecordDecl*, 8> Queue; | |||
2156 | ||||
2157 | Class = Class->getCanonicalDecl(); | |||
2158 | while (true) { | |||
2159 | for (const auto &I : Current->bases()) { | |||
2160 | CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); | |||
2161 | if (!Base) | |||
2162 | continue; | |||
2163 | ||||
2164 | Base = Base->getDefinition(); | |||
2165 | if (!Base) | |||
2166 | continue; | |||
2167 | ||||
2168 | if (Base->getCanonicalDecl() == Class) | |||
2169 | return true; | |||
2170 | ||||
2171 | Queue.push_back(Base); | |||
2172 | } | |||
2173 | ||||
2174 | if (Queue.empty()) | |||
2175 | return false; | |||
2176 | ||||
2177 | Current = Queue.pop_back_val(); | |||
2178 | } | |||
2179 | ||||
2180 | return false; | |||
2181 | } | |||
2182 | ||||
2183 | /// Check the validity of a C++ base class specifier. | |||
2184 | /// | |||
2185 | /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics | |||
2186 | /// and returns NULL otherwise. | |||
2187 | CXXBaseSpecifier * | |||
2188 | Sema::CheckBaseSpecifier(CXXRecordDecl *Class, | |||
2189 | SourceRange SpecifierRange, | |||
2190 | bool Virtual, AccessSpecifier Access, | |||
2191 | TypeSourceInfo *TInfo, | |||
2192 | SourceLocation EllipsisLoc) { | |||
2193 | QualType BaseType = TInfo->getType(); | |||
2194 | ||||
2195 | // C++ [class.union]p1: | |||
2196 | // A union shall not have base classes. | |||
2197 | if (Class->isUnion()) { | |||
2198 | Diag(Class->getLocation(), diag::err_base_clause_on_union) | |||
2199 | << SpecifierRange; | |||
2200 | return nullptr; | |||
2201 | } | |||
2202 | ||||
2203 | if (EllipsisLoc.isValid() && | |||
2204 | !TInfo->getType()->containsUnexpandedParameterPack()) { | |||
2205 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
2206 | << TInfo->getTypeLoc().getSourceRange(); | |||
2207 | EllipsisLoc = SourceLocation(); | |||
2208 | } | |||
2209 | ||||
2210 | SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
2211 | ||||
2212 | if (BaseType->isDependentType()) { | |||
2213 | // Make sure that we don't have circular inheritance among our dependent | |||
2214 | // bases. For non-dependent bases, the check for completeness below handles | |||
2215 | // this. | |||
2216 | if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { | |||
2217 | if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || | |||
2218 | ((BaseDecl = BaseDecl->getDefinition()) && | |||
2219 | findCircularInheritance(Class, BaseDecl))) { | |||
2220 | Diag(BaseLoc, diag::err_circular_inheritance) | |||
2221 | << BaseType << Context.getTypeDeclType(Class); | |||
2222 | ||||
2223 | if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) | |||
2224 | Diag(BaseDecl->getLocation(), diag::note_previous_decl) | |||
2225 | << BaseType; | |||
2226 | ||||
2227 | return nullptr; | |||
2228 | } | |||
2229 | } | |||
2230 | ||||
2231 | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, | |||
2232 | Class->getTagKind() == TTK_Class, | |||
2233 | Access, TInfo, EllipsisLoc); | |||
2234 | } | |||
2235 | ||||
2236 | // Base specifiers must be record types. | |||
2237 | if (!BaseType->isRecordType()) { | |||
2238 | Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; | |||
2239 | return nullptr; | |||
2240 | } | |||
2241 | ||||
2242 | // C++ [class.union]p1: | |||
2243 | // A union shall not be used as a base class. | |||
2244 | if (BaseType->isUnionType()) { | |||
2245 | Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; | |||
2246 | return nullptr; | |||
2247 | } | |||
2248 | ||||
2249 | // For the MS ABI, propagate DLL attributes to base class templates. | |||
2250 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
2251 | if (Attr *ClassAttr = getDLLAttr(Class)) { | |||
2252 | if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( | |||
2253 | BaseType->getAsCXXRecordDecl())) { | |||
2254 | propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, | |||
2255 | BaseLoc); | |||
2256 | } | |||
2257 | } | |||
2258 | } | |||
2259 | ||||
2260 | // C++ [class.derived]p2: | |||
2261 | // The class-name in a base-specifier shall not be an incompletely | |||
2262 | // defined class. | |||
2263 | if (RequireCompleteType(BaseLoc, BaseType, | |||
2264 | diag::err_incomplete_base_class, SpecifierRange)) { | |||
2265 | Class->setInvalidDecl(); | |||
2266 | return nullptr; | |||
2267 | } | |||
2268 | ||||
2269 | // If the base class is polymorphic or isn't empty, the new one is/isn't, too. | |||
2270 | RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); | |||
2271 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2271, __PRETTY_FUNCTION__)); | |||
2272 | BaseDecl = BaseDecl->getDefinition(); | |||
2273 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2273, __PRETTY_FUNCTION__)); | |||
2274 | CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); | |||
2275 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2275, __PRETTY_FUNCTION__)); | |||
2276 | ||||
2277 | // Microsoft docs say: | |||
2278 | // "If a base-class has a code_seg attribute, derived classes must have the | |||
2279 | // same attribute." | |||
2280 | const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); | |||
2281 | const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); | |||
2282 | if ((DerivedCSA || BaseCSA) && | |||
2283 | (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { | |||
2284 | Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); | |||
2285 | Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) | |||
2286 | << CXXBaseDecl; | |||
2287 | return nullptr; | |||
2288 | } | |||
2289 | ||||
2290 | // A class which contains a flexible array member is not suitable for use as a | |||
2291 | // base class: | |||
2292 | // - If the layout determines that a base comes before another base, | |||
2293 | // the flexible array member would index into the subsequent base. | |||
2294 | // - If the layout determines that base comes before the derived class, | |||
2295 | // the flexible array member would index into the derived class. | |||
2296 | if (CXXBaseDecl->hasFlexibleArrayMember()) { | |||
2297 | Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) | |||
2298 | << CXXBaseDecl->getDeclName(); | |||
2299 | return nullptr; | |||
2300 | } | |||
2301 | ||||
2302 | // C++ [class]p3: | |||
2303 | // If a class is marked final and it appears as a base-type-specifier in | |||
2304 | // base-clause, the program is ill-formed. | |||
2305 | if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { | |||
2306 | Diag(BaseLoc, diag::err_class_marked_final_used_as_base) | |||
2307 | << CXXBaseDecl->getDeclName() | |||
2308 | << FA->isSpelledAsSealed(); | |||
2309 | Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) | |||
2310 | << CXXBaseDecl->getDeclName() << FA->getRange(); | |||
2311 | return nullptr; | |||
2312 | } | |||
2313 | ||||
2314 | if (BaseDecl->isInvalidDecl()) | |||
2315 | Class->setInvalidDecl(); | |||
2316 | ||||
2317 | // Create the base specifier. | |||
2318 | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, | |||
2319 | Class->getTagKind() == TTK_Class, | |||
2320 | Access, TInfo, EllipsisLoc); | |||
2321 | } | |||
2322 | ||||
2323 | /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is | |||
2324 | /// one entry in the base class list of a class specifier, for | |||
2325 | /// example: | |||
2326 | /// class foo : public bar, virtual private baz { | |||
2327 | /// 'public bar' and 'virtual private baz' are each base-specifiers. | |||
2328 | BaseResult | |||
2329 | Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, | |||
2330 | ParsedAttributes &Attributes, | |||
2331 | bool Virtual, AccessSpecifier Access, | |||
2332 | ParsedType basetype, SourceLocation BaseLoc, | |||
2333 | SourceLocation EllipsisLoc) { | |||
2334 | if (!classdecl) | |||
2335 | return true; | |||
2336 | ||||
2337 | AdjustDeclIfTemplate(classdecl); | |||
2338 | CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); | |||
2339 | if (!Class) | |||
2340 | return true; | |||
2341 | ||||
2342 | // We haven't yet attached the base specifiers. | |||
2343 | Class->setIsParsingBaseSpecifiers(); | |||
2344 | ||||
2345 | // We do not support any C++11 attributes on base-specifiers yet. | |||
2346 | // Diagnose any attributes we see. | |||
2347 | for (const ParsedAttr &AL : Attributes) { | |||
2348 | if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) | |||
2349 | continue; | |||
2350 | Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute | |||
2351 | ? (unsigned)diag::warn_unknown_attribute_ignored | |||
2352 | : (unsigned)diag::err_base_specifier_attribute) | |||
2353 | << AL.getName(); | |||
2354 | } | |||
2355 | ||||
2356 | TypeSourceInfo *TInfo = nullptr; | |||
2357 | GetTypeFromParser(basetype, &TInfo); | |||
2358 | ||||
2359 | if (EllipsisLoc.isInvalid() && | |||
2360 | DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, | |||
2361 | UPPC_BaseType)) | |||
2362 | return true; | |||
2363 | ||||
2364 | if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, | |||
2365 | Virtual, Access, TInfo, | |||
2366 | EllipsisLoc)) | |||
2367 | return BaseSpec; | |||
2368 | else | |||
2369 | Class->setInvalidDecl(); | |||
2370 | ||||
2371 | return true; | |||
2372 | } | |||
2373 | ||||
2374 | /// Use small set to collect indirect bases. As this is only used | |||
2375 | /// locally, there's no need to abstract the small size parameter. | |||
2376 | typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; | |||
2377 | ||||
2378 | /// Recursively add the bases of Type. Don't add Type itself. | |||
2379 | static void | |||
2380 | NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, | |||
2381 | const QualType &Type) | |||
2382 | { | |||
2383 | // Even though the incoming type is a base, it might not be | |||
2384 | // a class -- it could be a template parm, for instance. | |||
2385 | if (auto Rec = Type->getAs<RecordType>()) { | |||
2386 | auto Decl = Rec->getAsCXXRecordDecl(); | |||
2387 | ||||
2388 | // Iterate over its bases. | |||
2389 | for (const auto &BaseSpec : Decl->bases()) { | |||
2390 | QualType Base = Context.getCanonicalType(BaseSpec.getType()) | |||
2391 | .getUnqualifiedType(); | |||
2392 | if (Set.insert(Base).second) | |||
2393 | // If we've not already seen it, recurse. | |||
2394 | NoteIndirectBases(Context, Set, Base); | |||
2395 | } | |||
2396 | } | |||
2397 | } | |||
2398 | ||||
2399 | /// Performs the actual work of attaching the given base class | |||
2400 | /// specifiers to a C++ class. | |||
2401 | bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, | |||
2402 | MutableArrayRef<CXXBaseSpecifier *> Bases) { | |||
2403 | if (Bases.empty()) | |||
2404 | return false; | |||
2405 | ||||
2406 | // Used to keep track of which base types we have already seen, so | |||
2407 | // that we can properly diagnose redundant direct base types. Note | |||
2408 | // that the key is always the unqualified canonical type of the base | |||
2409 | // class. | |||
2410 | std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; | |||
2411 | ||||
2412 | // Used to track indirect bases so we can see if a direct base is | |||
2413 | // ambiguous. | |||
2414 | IndirectBaseSet IndirectBaseTypes; | |||
2415 | ||||
2416 | // Copy non-redundant base specifiers into permanent storage. | |||
2417 | unsigned NumGoodBases = 0; | |||
2418 | bool Invalid = false; | |||
2419 | for (unsigned idx = 0; idx < Bases.size(); ++idx) { | |||
2420 | QualType NewBaseType | |||
2421 | = Context.getCanonicalType(Bases[idx]->getType()); | |||
2422 | NewBaseType = NewBaseType.getLocalUnqualifiedType(); | |||
2423 | ||||
2424 | CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; | |||
2425 | if (KnownBase) { | |||
2426 | // C++ [class.mi]p3: | |||
2427 | // A class shall not be specified as a direct base class of a | |||
2428 | // derived class more than once. | |||
2429 | Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) | |||
2430 | << KnownBase->getType() << Bases[idx]->getSourceRange(); | |||
2431 | ||||
2432 | // Delete the duplicate base class specifier; we're going to | |||
2433 | // overwrite its pointer later. | |||
2434 | Context.Deallocate(Bases[idx]); | |||
2435 | ||||
2436 | Invalid = true; | |||
2437 | } else { | |||
2438 | // Okay, add this new base class. | |||
2439 | KnownBase = Bases[idx]; | |||
2440 | Bases[NumGoodBases++] = Bases[idx]; | |||
2441 | ||||
2442 | // Note this base's direct & indirect bases, if there could be ambiguity. | |||
2443 | if (Bases.size() > 1) | |||
2444 | NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); | |||
2445 | ||||
2446 | if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { | |||
2447 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); | |||
2448 | if (Class->isInterface() && | |||
2449 | (!RD->isInterfaceLike() || | |||
2450 | KnownBase->getAccessSpecifier() != AS_public)) { | |||
2451 | // The Microsoft extension __interface does not permit bases that | |||
2452 | // are not themselves public interfaces. | |||
2453 | Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) | |||
2454 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD | |||
2455 | << RD->getSourceRange(); | |||
2456 | Invalid = true; | |||
2457 | } | |||
2458 | if (RD->hasAttr<WeakAttr>()) | |||
2459 | Class->addAttr(WeakAttr::CreateImplicit(Context)); | |||
2460 | } | |||
2461 | } | |||
2462 | } | |||
2463 | ||||
2464 | // Attach the remaining base class specifiers to the derived class. | |||
2465 | Class->setBases(Bases.data(), NumGoodBases); | |||
2466 | ||||
2467 | // Check that the only base classes that are duplicate are virtual. | |||
2468 | for (unsigned idx = 0; idx < NumGoodBases; ++idx) { | |||
2469 | // Check whether this direct base is inaccessible due to ambiguity. | |||
2470 | QualType BaseType = Bases[idx]->getType(); | |||
2471 | ||||
2472 | // Skip all dependent types in templates being used as base specifiers. | |||
2473 | // Checks below assume that the base specifier is a CXXRecord. | |||
2474 | if (BaseType->isDependentType()) | |||
2475 | continue; | |||
2476 | ||||
2477 | CanQualType CanonicalBase = Context.getCanonicalType(BaseType) | |||
2478 | .getUnqualifiedType(); | |||
2479 | ||||
2480 | if (IndirectBaseTypes.count(CanonicalBase)) { | |||
2481 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
2482 | /*DetectVirtual=*/true); | |||
2483 | bool found | |||
2484 | = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); | |||
2485 | assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2485, __PRETTY_FUNCTION__)); | |||
2486 | (void)found; | |||
2487 | ||||
2488 | if (Paths.isAmbiguous(CanonicalBase)) | |||
2489 | Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) | |||
2490 | << BaseType << getAmbiguousPathsDisplayString(Paths) | |||
2491 | << Bases[idx]->getSourceRange(); | |||
2492 | else | |||
2493 | assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) : __assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2493, __PRETTY_FUNCTION__)); | |||
2494 | } | |||
2495 | ||||
2496 | // Delete the base class specifier, since its data has been copied | |||
2497 | // into the CXXRecordDecl. | |||
2498 | Context.Deallocate(Bases[idx]); | |||
2499 | } | |||
2500 | ||||
2501 | return Invalid; | |||
2502 | } | |||
2503 | ||||
2504 | /// ActOnBaseSpecifiers - Attach the given base specifiers to the | |||
2505 | /// class, after checking whether there are any duplicate base | |||
2506 | /// classes. | |||
2507 | void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, | |||
2508 | MutableArrayRef<CXXBaseSpecifier *> Bases) { | |||
2509 | if (!ClassDecl || Bases.empty()) | |||
2510 | return; | |||
2511 | ||||
2512 | AdjustDeclIfTemplate(ClassDecl); | |||
2513 | AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); | |||
2514 | } | |||
2515 | ||||
2516 | /// Determine whether the type \p Derived is a C++ class that is | |||
2517 | /// derived from the type \p Base. | |||
2518 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { | |||
2519 | if (!getLangOpts().CPlusPlus) | |||
2520 | return false; | |||
2521 | ||||
2522 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); | |||
2523 | if (!DerivedRD) | |||
2524 | return false; | |||
2525 | ||||
2526 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); | |||
2527 | if (!BaseRD) | |||
2528 | return false; | |||
2529 | ||||
2530 | // If either the base or the derived type is invalid, don't try to | |||
2531 | // check whether one is derived from the other. | |||
2532 | if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) | |||
2533 | return false; | |||
2534 | ||||
2535 | // FIXME: In a modules build, do we need the entire path to be visible for us | |||
2536 | // to be able to use the inheritance relationship? | |||
2537 | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) | |||
2538 | return false; | |||
2539 | ||||
2540 | return DerivedRD->isDerivedFrom(BaseRD); | |||
2541 | } | |||
2542 | ||||
2543 | /// Determine whether the type \p Derived is a C++ class that is | |||
2544 | /// derived from the type \p Base. | |||
2545 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, | |||
2546 | CXXBasePaths &Paths) { | |||
2547 | if (!getLangOpts().CPlusPlus) | |||
2548 | return false; | |||
2549 | ||||
2550 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); | |||
2551 | if (!DerivedRD) | |||
2552 | return false; | |||
2553 | ||||
2554 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); | |||
2555 | if (!BaseRD) | |||
2556 | return false; | |||
2557 | ||||
2558 | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) | |||
2559 | return false; | |||
2560 | ||||
2561 | return DerivedRD->isDerivedFrom(BaseRD, Paths); | |||
2562 | } | |||
2563 | ||||
2564 | static void BuildBasePathArray(const CXXBasePath &Path, | |||
2565 | CXXCastPath &BasePathArray) { | |||
2566 | // We first go backward and check if we have a virtual base. | |||
2567 | // FIXME: It would be better if CXXBasePath had the base specifier for | |||
2568 | // the nearest virtual base. | |||
2569 | unsigned Start = 0; | |||
2570 | for (unsigned I = Path.size(); I != 0; --I) { | |||
2571 | if (Path[I - 1].Base->isVirtual()) { | |||
2572 | Start = I - 1; | |||
2573 | break; | |||
2574 | } | |||
2575 | } | |||
2576 | ||||
2577 | // Now add all bases. | |||
2578 | for (unsigned I = Start, E = Path.size(); I != E; ++I) | |||
2579 | BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); | |||
2580 | } | |||
2581 | ||||
2582 | ||||
2583 | void Sema::BuildBasePathArray(const CXXBasePaths &Paths, | |||
2584 | CXXCastPath &BasePathArray) { | |||
2585 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2585, __PRETTY_FUNCTION__)); | |||
2586 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2586, __PRETTY_FUNCTION__)); | |||
2587 | return ::BuildBasePathArray(Paths.front(), BasePathArray); | |||
2588 | } | |||
2589 | /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base | |||
2590 | /// conversion (where Derived and Base are class types) is | |||
2591 | /// well-formed, meaning that the conversion is unambiguous (and | |||
2592 | /// that all of the base classes are accessible). Returns true | |||
2593 | /// and emits a diagnostic if the code is ill-formed, returns false | |||
2594 | /// otherwise. Loc is the location where this routine should point to | |||
2595 | /// if there is an error, and Range is the source range to highlight | |||
2596 | /// if there is an error. | |||
2597 | /// | |||
2598 | /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the | |||
2599 | /// diagnostic for the respective type of error will be suppressed, but the | |||
2600 | /// check for ill-formed code will still be performed. | |||
2601 | bool | |||
2602 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, | |||
2603 | unsigned InaccessibleBaseID, | |||
2604 | unsigned AmbigiousBaseConvID, | |||
2605 | SourceLocation Loc, SourceRange Range, | |||
2606 | DeclarationName Name, | |||
2607 | CXXCastPath *BasePath, | |||
2608 | bool IgnoreAccess) { | |||
2609 | // First, determine whether the path from Derived to Base is | |||
2610 | // ambiguous. This is slightly more expensive than checking whether | |||
2611 | // the Derived to Base conversion exists, because here we need to | |||
2612 | // explore multiple paths to determine if there is an ambiguity. | |||
2613 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
2614 | /*DetectVirtual=*/false); | |||
2615 | bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); | |||
2616 | if (!DerivationOkay) | |||
2617 | return true; | |||
2618 | ||||
2619 | const CXXBasePath *Path = nullptr; | |||
2620 | if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) | |||
2621 | Path = &Paths.front(); | |||
2622 | ||||
2623 | // For MSVC compatibility, check if Derived directly inherits from Base. Clang | |||
2624 | // warns about this hierarchy under -Winaccessible-base, but MSVC allows the | |||
2625 | // user to access such bases. | |||
2626 | if (!Path && getLangOpts().MSVCCompat) { | |||
2627 | for (const CXXBasePath &PossiblePath : Paths) { | |||
2628 | if (PossiblePath.size() == 1) { | |||
2629 | Path = &PossiblePath; | |||
2630 | if (AmbigiousBaseConvID) | |||
2631 | Diag(Loc, diag::ext_ms_ambiguous_direct_base) | |||
2632 | << Base << Derived << Range; | |||
2633 | break; | |||
2634 | } | |||
2635 | } | |||
2636 | } | |||
2637 | ||||
2638 | if (Path) { | |||
2639 | if (!IgnoreAccess) { | |||
2640 | // Check that the base class can be accessed. | |||
2641 | switch ( | |||
2642 | CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { | |||
2643 | case AR_inaccessible: | |||
2644 | return true; | |||
2645 | case AR_accessible: | |||
2646 | case AR_dependent: | |||
2647 | case AR_delayed: | |||
2648 | break; | |||
2649 | } | |||
2650 | } | |||
2651 | ||||
2652 | // Build a base path if necessary. | |||
2653 | if (BasePath) | |||
2654 | ::BuildBasePathArray(*Path, *BasePath); | |||
2655 | return false; | |||
2656 | } | |||
2657 | ||||
2658 | if (AmbigiousBaseConvID) { | |||
2659 | // We know that the derived-to-base conversion is ambiguous, and | |||
2660 | // we're going to produce a diagnostic. Perform the derived-to-base | |||
2661 | // search just one more time to compute all of the possible paths so | |||
2662 | // that we can print them out. This is more expensive than any of | |||
2663 | // the previous derived-to-base checks we've done, but at this point | |||
2664 | // performance isn't as much of an issue. | |||
2665 | Paths.clear(); | |||
2666 | Paths.setRecordingPaths(true); | |||
2667 | bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); | |||
2668 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2668, __PRETTY_FUNCTION__)); | |||
2669 | (void)StillOkay; | |||
2670 | ||||
2671 | // Build up a textual representation of the ambiguous paths, e.g., | |||
2672 | // D -> B -> A, that will be used to illustrate the ambiguous | |||
2673 | // conversions in the diagnostic. We only print one of the paths | |||
2674 | // to each base class subobject. | |||
2675 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); | |||
2676 | ||||
2677 | Diag(Loc, AmbigiousBaseConvID) | |||
2678 | << Derived << Base << PathDisplayStr << Range << Name; | |||
2679 | } | |||
2680 | return true; | |||
2681 | } | |||
2682 | ||||
2683 | bool | |||
2684 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, | |||
2685 | SourceLocation Loc, SourceRange Range, | |||
2686 | CXXCastPath *BasePath, | |||
2687 | bool IgnoreAccess) { | |||
2688 | return CheckDerivedToBaseConversion( | |||
2689 | Derived, Base, diag::err_upcast_to_inaccessible_base, | |||
2690 | diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), | |||
2691 | BasePath, IgnoreAccess); | |||
2692 | } | |||
2693 | ||||
2694 | ||||
2695 | /// Builds a string representing ambiguous paths from a | |||
2696 | /// specific derived class to different subobjects of the same base | |||
2697 | /// class. | |||
2698 | /// | |||
2699 | /// This function builds a string that can be used in error messages | |||
2700 | /// to show the different paths that one can take through the | |||
2701 | /// inheritance hierarchy to go from the derived class to different | |||
2702 | /// subobjects of a base class. The result looks something like this: | |||
2703 | /// @code | |||
2704 | /// struct D -> struct B -> struct A | |||
2705 | /// struct D -> struct C -> struct A | |||
2706 | /// @endcode | |||
2707 | std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { | |||
2708 | std::string PathDisplayStr; | |||
2709 | std::set<unsigned> DisplayedPaths; | |||
2710 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); | |||
2711 | Path != Paths.end(); ++Path) { | |||
2712 | if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { | |||
2713 | // We haven't displayed a path to this particular base | |||
2714 | // class subobject yet. | |||
2715 | PathDisplayStr += "\n "; | |||
2716 | PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); | |||
2717 | for (CXXBasePath::const_iterator Element = Path->begin(); | |||
2718 | Element != Path->end(); ++Element) | |||
2719 | PathDisplayStr += " -> " + Element->Base->getType().getAsString(); | |||
2720 | } | |||
2721 | } | |||
2722 | ||||
2723 | return PathDisplayStr; | |||
2724 | } | |||
2725 | ||||
2726 | //===----------------------------------------------------------------------===// | |||
2727 | // C++ class member Handling | |||
2728 | //===----------------------------------------------------------------------===// | |||
2729 | ||||
2730 | /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. | |||
2731 | bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, | |||
2732 | SourceLocation ColonLoc, | |||
2733 | const ParsedAttributesView &Attrs) { | |||
2734 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2734, __PRETTY_FUNCTION__)); | |||
2735 | AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, | |||
2736 | ASLoc, ColonLoc); | |||
2737 | CurContext->addHiddenDecl(ASDecl); | |||
2738 | return ProcessAccessDeclAttributeList(ASDecl, Attrs); | |||
2739 | } | |||
2740 | ||||
2741 | /// CheckOverrideControl - Check C++11 override control semantics. | |||
2742 | void Sema::CheckOverrideControl(NamedDecl *D) { | |||
2743 | if (D->isInvalidDecl()) | |||
2744 | return; | |||
2745 | ||||
2746 | // We only care about "override" and "final" declarations. | |||
2747 | if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) | |||
2748 | return; | |||
2749 | ||||
2750 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); | |||
2751 | ||||
2752 | // We can't check dependent instance methods. | |||
2753 | if (MD && MD->isInstance() && | |||
2754 | (MD->getParent()->hasAnyDependentBases() || | |||
2755 | MD->getType()->isDependentType())) | |||
2756 | return; | |||
2757 | ||||
2758 | if (MD && !MD->isVirtual()) { | |||
2759 | // If we have a non-virtual method, check if if hides a virtual method. | |||
2760 | // (In that case, it's most likely the method has the wrong type.) | |||
2761 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
2762 | FindHiddenVirtualMethods(MD, OverloadedMethods); | |||
2763 | ||||
2764 | if (!OverloadedMethods.empty()) { | |||
2765 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { | |||
2766 | Diag(OA->getLocation(), | |||
2767 | diag::override_keyword_hides_virtual_member_function) | |||
2768 | << "override" << (OverloadedMethods.size() > 1); | |||
2769 | } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { | |||
2770 | Diag(FA->getLocation(), | |||
2771 | diag::override_keyword_hides_virtual_member_function) | |||
2772 | << (FA->isSpelledAsSealed() ? "sealed" : "final") | |||
2773 | << (OverloadedMethods.size() > 1); | |||
2774 | } | |||
2775 | NoteHiddenVirtualMethods(MD, OverloadedMethods); | |||
2776 | MD->setInvalidDecl(); | |||
2777 | return; | |||
2778 | } | |||
2779 | // Fall through into the general case diagnostic. | |||
2780 | // FIXME: We might want to attempt typo correction here. | |||
2781 | } | |||
2782 | ||||
2783 | if (!MD || !MD->isVirtual()) { | |||
2784 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { | |||
2785 | Diag(OA->getLocation(), | |||
2786 | diag::override_keyword_only_allowed_on_virtual_member_functions) | |||
2787 | << "override" << FixItHint::CreateRemoval(OA->getLocation()); | |||
2788 | D->dropAttr<OverrideAttr>(); | |||
2789 | } | |||
2790 | if (FinalAttr *FA = D->getAttr<FinalAttr>()) { | |||
2791 | Diag(FA->getLocation(), | |||
2792 | diag::override_keyword_only_allowed_on_virtual_member_functions) | |||
2793 | << (FA->isSpelledAsSealed() ? "sealed" : "final") | |||
2794 | << FixItHint::CreateRemoval(FA->getLocation()); | |||
2795 | D->dropAttr<FinalAttr>(); | |||
2796 | } | |||
2797 | return; | |||
2798 | } | |||
2799 | ||||
2800 | // C++11 [class.virtual]p5: | |||
2801 | // If a function is marked with the virt-specifier override and | |||
2802 | // does not override a member function of a base class, the program is | |||
2803 | // ill-formed. | |||
2804 | bool HasOverriddenMethods = MD->size_overridden_methods() != 0; | |||
2805 | if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) | |||
2806 | Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) | |||
2807 | << MD->getDeclName(); | |||
2808 | } | |||
2809 | ||||
2810 | void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { | |||
2811 | if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) | |||
2812 | return; | |||
2813 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); | |||
2814 | if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) | |||
2815 | return; | |||
2816 | ||||
2817 | SourceLocation Loc = MD->getLocation(); | |||
2818 | SourceLocation SpellingLoc = Loc; | |||
2819 | if (getSourceManager().isMacroArgExpansion(Loc)) | |||
2820 | SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); | |||
2821 | SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); | |||
2822 | if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) | |||
2823 | return; | |||
2824 | ||||
2825 | if (MD->size_overridden_methods() > 0) { | |||
2826 | unsigned DiagID = isa<CXXDestructorDecl>(MD) | |||
2827 | ? diag::warn_destructor_marked_not_override_overriding | |||
2828 | : diag::warn_function_marked_not_override_overriding; | |||
2829 | Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | |||
2830 | const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); | |||
2831 | Diag(OMD->getLocation(), diag::note_overridden_virtual_function); | |||
2832 | } | |||
2833 | } | |||
2834 | ||||
2835 | /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member | |||
2836 | /// function overrides a virtual member function marked 'final', according to | |||
2837 | /// C++11 [class.virtual]p4. | |||
2838 | bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, | |||
2839 | const CXXMethodDecl *Old) { | |||
2840 | FinalAttr *FA = Old->getAttr<FinalAttr>(); | |||
2841 | if (!FA) | |||
2842 | return false; | |||
2843 | ||||
2844 | Diag(New->getLocation(), diag::err_final_function_overridden) | |||
2845 | << New->getDeclName() | |||
2846 | << FA->isSpelledAsSealed(); | |||
2847 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); | |||
2848 | return true; | |||
2849 | } | |||
2850 | ||||
2851 | static bool InitializationHasSideEffects(const FieldDecl &FD) { | |||
2852 | const Type *T = FD.getType()->getBaseElementTypeUnsafe(); | |||
2853 | // FIXME: Destruction of ObjC lifetime types has side-effects. | |||
2854 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
2855 | return !RD->isCompleteDefinition() || | |||
2856 | !RD->hasTrivialDefaultConstructor() || | |||
2857 | !RD->hasTrivialDestructor(); | |||
2858 | return false; | |||
2859 | } | |||
2860 | ||||
2861 | static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { | |||
2862 | ParsedAttributesView::const_iterator Itr = | |||
2863 | llvm::find_if(list, [](const ParsedAttr &AL) { | |||
2864 | return AL.isDeclspecPropertyAttribute(); | |||
2865 | }); | |||
2866 | if (Itr != list.end()) | |||
2867 | return &*Itr; | |||
2868 | return nullptr; | |||
2869 | } | |||
2870 | ||||
2871 | // Check if there is a field shadowing. | |||
2872 | void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, | |||
2873 | DeclarationName FieldName, | |||
2874 | const CXXRecordDecl *RD, | |||
2875 | bool DeclIsField) { | |||
2876 | if (Diags.isIgnored(diag::warn_shadow_field, Loc)) | |||
2877 | return; | |||
2878 | ||||
2879 | // To record a shadowed field in a base | |||
2880 | std::map<CXXRecordDecl*, NamedDecl*> Bases; | |||
2881 | auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, | |||
2882 | CXXBasePath &Path) { | |||
2883 | const auto Base = Specifier->getType()->getAsCXXRecordDecl(); | |||
2884 | // Record an ambiguous path directly | |||
2885 | if (Bases.find(Base) != Bases.end()) | |||
2886 | return true; | |||
2887 | for (const auto Field : Base->lookup(FieldName)) { | |||
2888 | if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && | |||
2889 | Field->getAccess() != AS_private) { | |||
2890 | assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void> (0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2890, __PRETTY_FUNCTION__)); | |||
2891 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2891, __PRETTY_FUNCTION__)); | |||
2892 | Bases[Base] = Field; | |||
2893 | return true; | |||
2894 | } | |||
2895 | } | |||
2896 | return false; | |||
2897 | }; | |||
2898 | ||||
2899 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
2900 | /*DetectVirtual=*/true); | |||
2901 | if (!RD->lookupInBases(FieldShadowed, Paths)) | |||
2902 | return; | |||
2903 | ||||
2904 | for (const auto &P : Paths) { | |||
2905 | auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); | |||
2906 | auto It = Bases.find(Base); | |||
2907 | // Skip duplicated bases | |||
2908 | if (It == Bases.end()) | |||
2909 | continue; | |||
2910 | auto BaseField = It->second; | |||
2911 | assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void > (0) : __assert_fail ("BaseField->getAccess() != AS_private" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2911, __PRETTY_FUNCTION__)); | |||
2912 | if (AS_none != | |||
2913 | CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { | |||
2914 | Diag(Loc, diag::warn_shadow_field) | |||
2915 | << FieldName << RD << Base << DeclIsField; | |||
2916 | Diag(BaseField->getLocation(), diag::note_shadow_field); | |||
2917 | Bases.erase(It); | |||
2918 | } | |||
2919 | } | |||
2920 | } | |||
2921 | ||||
2922 | /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member | |||
2923 | /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the | |||
2924 | /// bitfield width if there is one, 'InitExpr' specifies the initializer if | |||
2925 | /// one has been parsed, and 'InitStyle' is set if an in-class initializer is | |||
2926 | /// present (but parsing it has been deferred). | |||
2927 | NamedDecl * | |||
2928 | Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, | |||
2929 | MultiTemplateParamsArg TemplateParameterLists, | |||
2930 | Expr *BW, const VirtSpecifiers &VS, | |||
2931 | InClassInitStyle InitStyle) { | |||
2932 | const DeclSpec &DS = D.getDeclSpec(); | |||
2933 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
2934 | DeclarationName Name = NameInfo.getName(); | |||
2935 | SourceLocation Loc = NameInfo.getLoc(); | |||
2936 | ||||
2937 | // For anonymous bitfields, the location should point to the type. | |||
2938 | if (Loc.isInvalid()) | |||
2939 | Loc = D.getBeginLoc(); | |||
2940 | ||||
2941 | Expr *BitWidth = static_cast<Expr*>(BW); | |||
2942 | ||||
2943 | assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void > (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2943, __PRETTY_FUNCTION__)); | |||
2944 | assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail ("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2944, __PRETTY_FUNCTION__)); | |||
2945 | ||||
2946 | bool isFunc = D.isDeclarationOfFunction(); | |||
2947 | const ParsedAttr *MSPropertyAttr = | |||
2948 | getMSPropertyAttr(D.getDeclSpec().getAttributes()); | |||
2949 | ||||
2950 | if (cast<CXXRecordDecl>(CurContext)->isInterface()) { | |||
2951 | // The Microsoft extension __interface only permits public member functions | |||
2952 | // and prohibits constructors, destructors, operators, non-public member | |||
2953 | // functions, static methods and data members. | |||
2954 | unsigned InvalidDecl; | |||
2955 | bool ShowDeclName = true; | |||
2956 | if (!isFunc && | |||
2957 | (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) | |||
2958 | InvalidDecl = 0; | |||
2959 | else if (!isFunc) | |||
2960 | InvalidDecl = 1; | |||
2961 | else if (AS != AS_public) | |||
2962 | InvalidDecl = 2; | |||
2963 | else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) | |||
2964 | InvalidDecl = 3; | |||
2965 | else switch (Name.getNameKind()) { | |||
2966 | case DeclarationName::CXXConstructorName: | |||
2967 | InvalidDecl = 4; | |||
2968 | ShowDeclName = false; | |||
2969 | break; | |||
2970 | ||||
2971 | case DeclarationName::CXXDestructorName: | |||
2972 | InvalidDecl = 5; | |||
2973 | ShowDeclName = false; | |||
2974 | break; | |||
2975 | ||||
2976 | case DeclarationName::CXXOperatorName: | |||
2977 | case DeclarationName::CXXConversionFunctionName: | |||
2978 | InvalidDecl = 6; | |||
2979 | break; | |||
2980 | ||||
2981 | default: | |||
2982 | InvalidDecl = 0; | |||
2983 | break; | |||
2984 | } | |||
2985 | ||||
2986 | if (InvalidDecl) { | |||
2987 | if (ShowDeclName) | |||
2988 | Diag(Loc, diag::err_invalid_member_in_interface) | |||
2989 | << (InvalidDecl-1) << Name; | |||
2990 | else | |||
2991 | Diag(Loc, diag::err_invalid_member_in_interface) | |||
2992 | << (InvalidDecl-1) << ""; | |||
2993 | return nullptr; | |||
2994 | } | |||
2995 | } | |||
2996 | ||||
2997 | // C++ 9.2p6: A member shall not be declared to have automatic storage | |||
2998 | // duration (auto, register) or with the extern storage-class-specifier. | |||
2999 | // C++ 7.1.1p8: The mutable specifier can be applied only to names of class | |||
3000 | // data members and cannot be applied to names declared const or static, | |||
3001 | // and cannot be applied to reference members. | |||
3002 | switch (DS.getStorageClassSpec()) { | |||
3003 | case DeclSpec::SCS_unspecified: | |||
3004 | case DeclSpec::SCS_typedef: | |||
3005 | case DeclSpec::SCS_static: | |||
3006 | break; | |||
3007 | case DeclSpec::SCS_mutable: | |||
3008 | if (isFunc) { | |||
3009 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); | |||
3010 | ||||
3011 | // FIXME: It would be nicer if the keyword was ignored only for this | |||
3012 | // declarator. Otherwise we could get follow-up errors. | |||
3013 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
3014 | } | |||
3015 | break; | |||
3016 | default: | |||
3017 | Diag(DS.getStorageClassSpecLoc(), | |||
3018 | diag::err_storageclass_invalid_for_member); | |||
3019 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
3020 | break; | |||
3021 | } | |||
3022 | ||||
3023 | bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || | |||
3024 | DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && | |||
3025 | !isFunc); | |||
3026 | ||||
3027 | if (DS.isConstexprSpecified() && isInstField) { | |||
3028 | SemaDiagnosticBuilder B = | |||
3029 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); | |||
3030 | SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); | |||
3031 | if (InitStyle == ICIS_NoInit) { | |||
3032 | B << 0 << 0; | |||
3033 | if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) | |||
3034 | B << FixItHint::CreateRemoval(ConstexprLoc); | |||
3035 | else { | |||
3036 | B << FixItHint::CreateReplacement(ConstexprLoc, "const"); | |||
3037 | D.getMutableDeclSpec().ClearConstexprSpec(); | |||
3038 | const char *PrevSpec; | |||
3039 | unsigned DiagID; | |||
3040 | bool Failed = D.getMutableDeclSpec().SetTypeQual( | |||
3041 | DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); | |||
3042 | (void)Failed; | |||
3043 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3043, __PRETTY_FUNCTION__)); | |||
3044 | } | |||
3045 | } else { | |||
3046 | B << 1; | |||
3047 | const char *PrevSpec; | |||
3048 | unsigned DiagID; | |||
3049 | if (D.getMutableDeclSpec().SetStorageClassSpec( | |||
3050 | *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, | |||
3051 | Context.getPrintingPolicy())) { | |||
3052 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3053, __PRETTY_FUNCTION__)) | |||
3053 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3053, __PRETTY_FUNCTION__)); | |||
3054 | B << 1; | |||
3055 | } else { | |||
3056 | B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); | |||
3057 | isInstField = false; | |||
3058 | } | |||
3059 | } | |||
3060 | } | |||
3061 | ||||
3062 | NamedDecl *Member; | |||
3063 | if (isInstField) { | |||
3064 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | |||
3065 | ||||
3066 | // Data members must have identifiers for names. | |||
3067 | if (!Name.isIdentifier()) { | |||
3068 | Diag(Loc, diag::err_bad_variable_name) | |||
3069 | << Name; | |||
3070 | return nullptr; | |||
3071 | } | |||
3072 | ||||
3073 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
3074 | ||||
3075 | // Member field could not be with "template" keyword. | |||
3076 | // So TemplateParameterLists should be empty in this case. | |||
3077 | if (TemplateParameterLists.size()) { | |||
3078 | TemplateParameterList* TemplateParams = TemplateParameterLists[0]; | |||
3079 | if (TemplateParams->size()) { | |||
3080 | // There is no such thing as a member field template. | |||
3081 | Diag(D.getIdentifierLoc(), diag::err_template_member) | |||
3082 | << II | |||
3083 | << SourceRange(TemplateParams->getTemplateLoc(), | |||
3084 | TemplateParams->getRAngleLoc()); | |||
3085 | } else { | |||
3086 | // There is an extraneous 'template<>' for this member. | |||
3087 | Diag(TemplateParams->getTemplateLoc(), | |||
3088 | diag::err_template_member_noparams) | |||
3089 | << II | |||
3090 | << SourceRange(TemplateParams->getTemplateLoc(), | |||
3091 | TemplateParams->getRAngleLoc()); | |||
3092 | } | |||
3093 | return nullptr; | |||
3094 | } | |||
3095 | ||||
3096 | if (SS.isSet() && !SS.isInvalid()) { | |||
3097 | // The user provided a superfluous scope specifier inside a class | |||
3098 | // definition: | |||
3099 | // | |||
3100 | // class X { | |||
3101 | // int X::member; | |||
3102 | // }; | |||
3103 | if (DeclContext *DC = computeDeclContext(SS, false)) | |||
3104 | diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), | |||
3105 | D.getName().getKind() == | |||
3106 | UnqualifiedIdKind::IK_TemplateId); | |||
3107 | else | |||
3108 | Diag(D.getIdentifierLoc(), diag::err_member_qualification) | |||
3109 | << Name << SS.getRange(); | |||
3110 | ||||
3111 | SS.clear(); | |||
3112 | } | |||
3113 | ||||
3114 | if (MSPropertyAttr) { | |||
3115 | Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, | |||
3116 | BitWidth, InitStyle, AS, *MSPropertyAttr); | |||
3117 | if (!Member) | |||
3118 | return nullptr; | |||
3119 | isInstField = false; | |||
3120 | } else { | |||
3121 | Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, | |||
3122 | BitWidth, InitStyle, AS); | |||
3123 | if (!Member) | |||
3124 | return nullptr; | |||
3125 | } | |||
3126 | ||||
3127 | CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); | |||
3128 | } else { | |||
3129 | Member = HandleDeclarator(S, D, TemplateParameterLists); | |||
3130 | if (!Member) | |||
3131 | return nullptr; | |||
3132 | ||||
3133 | // Non-instance-fields can't have a bitfield. | |||
3134 | if (BitWidth) { | |||
3135 | if (Member->isInvalidDecl()) { | |||
3136 | // don't emit another diagnostic. | |||
3137 | } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { | |||
3138 | // C++ 9.6p3: A bit-field shall not be a static member. | |||
3139 | // "static member 'A' cannot be a bit-field" | |||
3140 | Diag(Loc, diag::err_static_not_bitfield) | |||
3141 | << Name << BitWidth->getSourceRange(); | |||
3142 | } else if (isa<TypedefDecl>(Member)) { | |||
3143 | // "typedef member 'x' cannot be a bit-field" | |||
3144 | Diag(Loc, diag::err_typedef_not_bitfield) | |||
3145 | << Name << BitWidth->getSourceRange(); | |||
3146 | } else { | |||
3147 | // A function typedef ("typedef int f(); f a;"). | |||
3148 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | |||
3149 | Diag(Loc, diag::err_not_integral_type_bitfield) | |||
3150 | << Name << cast<ValueDecl>(Member)->getType() | |||
3151 | << BitWidth->getSourceRange(); | |||
3152 | } | |||
3153 | ||||
3154 | BitWidth = nullptr; | |||
3155 | Member->setInvalidDecl(); | |||
3156 | } | |||
3157 | ||||
3158 | NamedDecl *NonTemplateMember = Member; | |||
3159 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) | |||
3160 | NonTemplateMember = FunTmpl->getTemplatedDecl(); | |||
3161 | else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) | |||
3162 | NonTemplateMember = VarTmpl->getTemplatedDecl(); | |||
3163 | ||||
3164 | Member->setAccess(AS); | |||
3165 | ||||
3166 | // If we have declared a member function template or static data member | |||
3167 | // template, set the access of the templated declaration as well. | |||
3168 | if (NonTemplateMember != Member) | |||
3169 | NonTemplateMember->setAccess(AS); | |||
3170 | ||||
3171 | // C++ [temp.deduct.guide]p3: | |||
3172 | // A deduction guide [...] for a member class template [shall be | |||
3173 | // declared] with the same access [as the template]. | |||
3174 | if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { | |||
3175 | auto *TD = DG->getDeducedTemplate(); | |||
3176 | // Access specifiers are only meaningful if both the template and the | |||
3177 | // deduction guide are from the same scope. | |||
3178 | if (AS != TD->getAccess() && | |||
3179 | TD->getDeclContext()->getRedeclContext()->Equals( | |||
3180 | DG->getDeclContext()->getRedeclContext())) { | |||
3181 | Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); | |||
3182 | Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) | |||
3183 | << TD->getAccess(); | |||
3184 | const AccessSpecDecl *LastAccessSpec = nullptr; | |||
3185 | for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { | |||
3186 | if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) | |||
3187 | LastAccessSpec = AccessSpec; | |||
3188 | } | |||
3189 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3189, __PRETTY_FUNCTION__)); | |||
3190 | Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) | |||
3191 | << AS; | |||
3192 | } | |||
3193 | } | |||
3194 | } | |||
3195 | ||||
3196 | if (VS.isOverrideSpecified()) | |||
3197 | Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); | |||
3198 | if (VS.isFinalSpecified()) | |||
3199 | Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, | |||
3200 | VS.isFinalSpelledSealed())); | |||
3201 | ||||
3202 | if (VS.getLastLocation().isValid()) { | |||
3203 | // Update the end location of a method that has a virt-specifiers. | |||
3204 | if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) | |||
3205 | MD->setRangeEnd(VS.getLastLocation()); | |||
3206 | } | |||
3207 | ||||
3208 | CheckOverrideControl(Member); | |||
3209 | ||||
3210 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3210, __PRETTY_FUNCTION__)); | |||
3211 | ||||
3212 | if (isInstField) { | |||
3213 | FieldDecl *FD = cast<FieldDecl>(Member); | |||
3214 | FieldCollector->Add(FD); | |||
3215 | ||||
3216 | if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { | |||
3217 | // Remember all explicit private FieldDecls that have a name, no side | |||
3218 | // effects and are not part of a dependent type declaration. | |||
3219 | if (!FD->isImplicit() && FD->getDeclName() && | |||
3220 | FD->getAccess() == AS_private && | |||
3221 | !FD->hasAttr<UnusedAttr>() && | |||
3222 | !FD->getParent()->isDependentContext() && | |||
3223 | !InitializationHasSideEffects(*FD)) | |||
3224 | UnusedPrivateFields.insert(FD); | |||
3225 | } | |||
3226 | } | |||
3227 | ||||
3228 | return Member; | |||
3229 | } | |||
3230 | ||||
3231 | namespace { | |||
3232 | class UninitializedFieldVisitor | |||
3233 | : public EvaluatedExprVisitor<UninitializedFieldVisitor> { | |||
3234 | Sema &S; | |||
3235 | // List of Decls to generate a warning on. Also remove Decls that become | |||
3236 | // initialized. | |||
3237 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls; | |||
3238 | // List of base classes of the record. Classes are removed after their | |||
3239 | // initializers. | |||
3240 | llvm::SmallPtrSetImpl<QualType> &BaseClasses; | |||
3241 | // Vector of decls to be removed from the Decl set prior to visiting the | |||
3242 | // nodes. These Decls may have been initialized in the prior initializer. | |||
3243 | llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; | |||
3244 | // If non-null, add a note to the warning pointing back to the constructor. | |||
3245 | const CXXConstructorDecl *Constructor; | |||
3246 | // Variables to hold state when processing an initializer list. When | |||
3247 | // InitList is true, special case initialization of FieldDecls matching | |||
3248 | // InitListFieldDecl. | |||
3249 | bool InitList; | |||
3250 | FieldDecl *InitListFieldDecl; | |||
3251 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | |||
3252 | ||||
3253 | public: | |||
3254 | typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; | |||
3255 | UninitializedFieldVisitor(Sema &S, | |||
3256 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls, | |||
3257 | llvm::SmallPtrSetImpl<QualType> &BaseClasses) | |||
3258 | : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), | |||
3259 | Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} | |||
3260 | ||||
3261 | // Returns true if the use of ME is not an uninitialized use. | |||
3262 | bool IsInitListMemberExprInitialized(MemberExpr *ME, | |||
3263 | bool CheckReferenceOnly) { | |||
3264 | llvm::SmallVector<FieldDecl*, 4> Fields; | |||
3265 | bool ReferenceField = false; | |||
3266 | while (ME) { | |||
3267 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
3268 | if (!FD) | |||
3269 | return false; | |||
3270 | Fields.push_back(FD); | |||
3271 | if (FD->getType()->isReferenceType()) | |||
3272 | ReferenceField = true; | |||
3273 | ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); | |||
3274 | } | |||
3275 | ||||
3276 | // Binding a reference to an uninitialized field is not an | |||
3277 | // uninitialized use. | |||
3278 | if (CheckReferenceOnly && !ReferenceField) | |||
3279 | return true; | |||
3280 | ||||
3281 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | |||
3282 | // Discard the first field since it is the field decl that is being | |||
3283 | // initialized. | |||
3284 | for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { | |||
3285 | UsedFieldIndex.push_back((*I)->getFieldIndex()); | |||
3286 | } | |||
3287 | ||||
3288 | for (auto UsedIter = UsedFieldIndex.begin(), | |||
3289 | UsedEnd = UsedFieldIndex.end(), | |||
3290 | OrigIter = InitFieldIndex.begin(), | |||
3291 | OrigEnd = InitFieldIndex.end(); | |||
3292 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | |||
3293 | if (*UsedIter < *OrigIter) | |||
3294 | return true; | |||
3295 | if (*UsedIter > *OrigIter) | |||
3296 | break; | |||
3297 | } | |||
3298 | ||||
3299 | return false; | |||
3300 | } | |||
3301 | ||||
3302 | void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, | |||
3303 | bool AddressOf) { | |||
3304 | if (isa<EnumConstantDecl>(ME->getMemberDecl())) | |||
3305 | return; | |||
3306 | ||||
3307 | // FieldME is the inner-most MemberExpr that is not an anonymous struct | |||
3308 | // or union. | |||
3309 | MemberExpr *FieldME = ME; | |||
3310 | ||||
3311 | bool AllPODFields = FieldME->getType().isPODType(S.Context); | |||
3312 | ||||
3313 | Expr *Base = ME; | |||
3314 | while (MemberExpr *SubME = | |||
3315 | dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { | |||
3316 | ||||
3317 | if (isa<VarDecl>(SubME->getMemberDecl())) | |||
3318 | return; | |||
3319 | ||||
3320 | if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) | |||
3321 | if (!FD->isAnonymousStructOrUnion()) | |||
3322 | FieldME = SubME; | |||
3323 | ||||
3324 | if (!FieldME->getType().isPODType(S.Context)) | |||
3325 | AllPODFields = false; | |||
3326 | ||||
3327 | Base = SubME->getBase(); | |||
3328 | } | |||
3329 | ||||
3330 | if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) | |||
3331 | return; | |||
3332 | ||||
3333 | if (AddressOf && AllPODFields) | |||
3334 | return; | |||
3335 | ||||
3336 | ValueDecl* FoundVD = FieldME->getMemberDecl(); | |||
3337 | ||||
3338 | if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { | |||
3339 | while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { | |||
3340 | BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); | |||
3341 | } | |||
3342 | ||||
3343 | if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { | |||
3344 | QualType T = BaseCast->getType(); | |||
3345 | if (T->isPointerType() && | |||
3346 | BaseClasses.count(T->getPointeeType())) { | |||
3347 | S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) | |||
3348 | << T->getPointeeType() << FoundVD; | |||
3349 | } | |||
3350 | } | |||
3351 | } | |||
3352 | ||||
3353 | if (!Decls.count(FoundVD)) | |||
3354 | return; | |||
3355 | ||||
3356 | const bool IsReference = FoundVD->getType()->isReferenceType(); | |||
3357 | ||||
3358 | if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { | |||
3359 | // Special checking for initializer lists. | |||
3360 | if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { | |||
3361 | return; | |||
3362 | } | |||
3363 | } else { | |||
3364 | // Prevent double warnings on use of unbounded references. | |||
3365 | if (CheckReferenceOnly && !IsReference) | |||
3366 | return; | |||
3367 | } | |||
3368 | ||||
3369 | unsigned diag = IsReference | |||
3370 | ? diag::warn_reference_field_is_uninit | |||
3371 | : diag::warn_field_is_uninit; | |||
3372 | S.Diag(FieldME->getExprLoc(), diag) << FoundVD; | |||
3373 | if (Constructor) | |||
3374 | S.Diag(Constructor->getLocation(), | |||
3375 | diag::note_uninit_in_this_constructor) | |||
3376 | << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); | |||
3377 | ||||
3378 | } | |||
3379 | ||||
3380 | void HandleValue(Expr *E, bool AddressOf) { | |||
3381 | E = E->IgnoreParens(); | |||
3382 | ||||
3383 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
3384 | HandleMemberExpr(ME, false /*CheckReferenceOnly*/, | |||
3385 | AddressOf /*AddressOf*/); | |||
3386 | return; | |||
3387 | } | |||
3388 | ||||
3389 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | |||
3390 | Visit(CO->getCond()); | |||
3391 | HandleValue(CO->getTrueExpr(), AddressOf); | |||
3392 | HandleValue(CO->getFalseExpr(), AddressOf); | |||
3393 | return; | |||
3394 | } | |||
3395 | ||||
3396 | if (BinaryConditionalOperator *BCO = | |||
3397 | dyn_cast<BinaryConditionalOperator>(E)) { | |||
3398 | Visit(BCO->getCond()); | |||
3399 | HandleValue(BCO->getFalseExpr(), AddressOf); | |||
3400 | return; | |||
3401 | } | |||
3402 | ||||
3403 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | |||
3404 | HandleValue(OVE->getSourceExpr(), AddressOf); | |||
3405 | return; | |||
3406 | } | |||
3407 | ||||
3408 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
3409 | switch (BO->getOpcode()) { | |||
3410 | default: | |||
3411 | break; | |||
3412 | case(BO_PtrMemD): | |||
3413 | case(BO_PtrMemI): | |||
3414 | HandleValue(BO->getLHS(), AddressOf); | |||
3415 | Visit(BO->getRHS()); | |||
3416 | return; | |||
3417 | case(BO_Comma): | |||
3418 | Visit(BO->getLHS()); | |||
3419 | HandleValue(BO->getRHS(), AddressOf); | |||
3420 | return; | |||
3421 | } | |||
3422 | } | |||
3423 | ||||
3424 | Visit(E); | |||
3425 | } | |||
3426 | ||||
3427 | void CheckInitListExpr(InitListExpr *ILE) { | |||
3428 | InitFieldIndex.push_back(0); | |||
3429 | for (auto Child : ILE->children()) { | |||
3430 | if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { | |||
3431 | CheckInitListExpr(SubList); | |||
3432 | } else { | |||
3433 | Visit(Child); | |||
3434 | } | |||
3435 | ++InitFieldIndex.back(); | |||
3436 | } | |||
3437 | InitFieldIndex.pop_back(); | |||
3438 | } | |||
3439 | ||||
3440 | void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, | |||
3441 | FieldDecl *Field, const Type *BaseClass) { | |||
3442 | // Remove Decls that may have been initialized in the previous | |||
3443 | // initializer. | |||
3444 | for (ValueDecl* VD : DeclsToRemove) | |||
3445 | Decls.erase(VD); | |||
3446 | DeclsToRemove.clear(); | |||
3447 | ||||
3448 | Constructor = FieldConstructor; | |||
3449 | InitListExpr *ILE = dyn_cast<InitListExpr>(E); | |||
3450 | ||||
3451 | if (ILE && Field) { | |||
3452 | InitList = true; | |||
3453 | InitListFieldDecl = Field; | |||
3454 | InitFieldIndex.clear(); | |||
3455 | CheckInitListExpr(ILE); | |||
3456 | } else { | |||
3457 | InitList = false; | |||
3458 | Visit(E); | |||
3459 | } | |||
3460 | ||||
3461 | if (Field) | |||
3462 | Decls.erase(Field); | |||
3463 | if (BaseClass) | |||
3464 | BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); | |||
3465 | } | |||
3466 | ||||
3467 | void VisitMemberExpr(MemberExpr *ME) { | |||
3468 | // All uses of unbounded reference fields will warn. | |||
3469 | HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); | |||
3470 | } | |||
3471 | ||||
3472 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
3473 | if (E->getCastKind() == CK_LValueToRValue) { | |||
3474 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | |||
3475 | return; | |||
3476 | } | |||
3477 | ||||
3478 | Inherited::VisitImplicitCastExpr(E); | |||
3479 | } | |||
3480 | ||||
3481 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
3482 | if (E->getConstructor()->isCopyConstructor()) { | |||
3483 | Expr *ArgExpr = E->getArg(0); | |||
3484 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | |||
3485 | if (ILE->getNumInits() == 1) | |||
3486 | ArgExpr = ILE->getInit(0); | |||
3487 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | |||
3488 | if (ICE->getCastKind() == CK_NoOp) | |||
3489 | ArgExpr = ICE->getSubExpr(); | |||
3490 | HandleValue(ArgExpr, false /*AddressOf*/); | |||
3491 | return; | |||
3492 | } | |||
3493 | Inherited::VisitCXXConstructExpr(E); | |||
3494 | } | |||
3495 | ||||
3496 | void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { | |||
3497 | Expr *Callee = E->getCallee(); | |||
3498 | if (isa<MemberExpr>(Callee)) { | |||
3499 | HandleValue(Callee, false /*AddressOf*/); | |||
3500 | for (auto Arg : E->arguments()) | |||
3501 | Visit(Arg); | |||
3502 | return; | |||
3503 | } | |||
3504 | ||||
3505 | Inherited::VisitCXXMemberCallExpr(E); | |||
3506 | } | |||
3507 | ||||
3508 | void VisitCallExpr(CallExpr *E) { | |||
3509 | // Treat std::move as a use. | |||
3510 | if (E->isCallToStdMove()) { | |||
3511 | HandleValue(E->getArg(0), /*AddressOf=*/false); | |||
3512 | return; | |||
3513 | } | |||
3514 | ||||
3515 | Inherited::VisitCallExpr(E); | |||
3516 | } | |||
3517 | ||||
3518 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
3519 | Expr *Callee = E->getCallee(); | |||
3520 | ||||
3521 | if (isa<UnresolvedLookupExpr>(Callee)) | |||
3522 | return Inherited::VisitCXXOperatorCallExpr(E); | |||
3523 | ||||
3524 | Visit(Callee); | |||
3525 | for (auto Arg : E->arguments()) | |||
3526 | HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); | |||
3527 | } | |||
3528 | ||||
3529 | void VisitBinaryOperator(BinaryOperator *E) { | |||
3530 | // If a field assignment is detected, remove the field from the | |||
3531 | // uninitiailized field set. | |||
3532 | if (E->getOpcode() == BO_Assign) | |||
3533 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) | |||
3534 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) | |||
3535 | if (!FD->getType()->isReferenceType()) | |||
3536 | DeclsToRemove.push_back(FD); | |||
3537 | ||||
3538 | if (E->isCompoundAssignmentOp()) { | |||
3539 | HandleValue(E->getLHS(), false /*AddressOf*/); | |||
3540 | Visit(E->getRHS()); | |||
3541 | return; | |||
3542 | } | |||
3543 | ||||
3544 | Inherited::VisitBinaryOperator(E); | |||
3545 | } | |||
3546 | ||||
3547 | void VisitUnaryOperator(UnaryOperator *E) { | |||
3548 | if (E->isIncrementDecrementOp()) { | |||
3549 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | |||
3550 | return; | |||
3551 | } | |||
3552 | if (E->getOpcode() == UO_AddrOf) { | |||
3553 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { | |||
3554 | HandleValue(ME->getBase(), true /*AddressOf*/); | |||
3555 | return; | |||
3556 | } | |||
3557 | } | |||
3558 | ||||
3559 | Inherited::VisitUnaryOperator(E); | |||
3560 | } | |||
3561 | }; | |||
3562 | ||||
3563 | // Diagnose value-uses of fields to initialize themselves, e.g. | |||
3564 | // foo(foo) | |||
3565 | // where foo is not also a parameter to the constructor. | |||
3566 | // Also diagnose across field uninitialized use such as | |||
3567 | // x(y), y(x) | |||
3568 | // TODO: implement -Wuninitialized and fold this into that framework. | |||
3569 | static void DiagnoseUninitializedFields( | |||
3570 | Sema &SemaRef, const CXXConstructorDecl *Constructor) { | |||
3571 | ||||
3572 | if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, | |||
3573 | Constructor->getLocation())) { | |||
3574 | return; | |||
3575 | } | |||
3576 | ||||
3577 | if (Constructor->isInvalidDecl()) | |||
3578 | return; | |||
3579 | ||||
3580 | const CXXRecordDecl *RD = Constructor->getParent(); | |||
3581 | ||||
3582 | if (RD->getDescribedClassTemplate()) | |||
3583 | return; | |||
3584 | ||||
3585 | // Holds fields that are uninitialized. | |||
3586 | llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; | |||
3587 | ||||
3588 | // At the beginning, all fields are uninitialized. | |||
3589 | for (auto *I : RD->decls()) { | |||
3590 | if (auto *FD = dyn_cast<FieldDecl>(I)) { | |||
3591 | UninitializedFields.insert(FD); | |||
3592 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { | |||
3593 | UninitializedFields.insert(IFD->getAnonField()); | |||
3594 | } | |||
3595 | } | |||
3596 | ||||
3597 | llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; | |||
3598 | for (auto I : RD->bases()) | |||
3599 | UninitializedBaseClasses.insert(I.getType().getCanonicalType()); | |||
3600 | ||||
3601 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | |||
3602 | return; | |||
3603 | ||||
3604 | UninitializedFieldVisitor UninitializedChecker(SemaRef, | |||
3605 | UninitializedFields, | |||
3606 | UninitializedBaseClasses); | |||
3607 | ||||
3608 | for (const auto *FieldInit : Constructor->inits()) { | |||
3609 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | |||
3610 | break; | |||
3611 | ||||
3612 | Expr *InitExpr = FieldInit->getInit(); | |||
3613 | if (!InitExpr) | |||
3614 | continue; | |||
3615 | ||||
3616 | if (CXXDefaultInitExpr *Default = | |||
3617 | dyn_cast<CXXDefaultInitExpr>(InitExpr)) { | |||
3618 | InitExpr = Default->getExpr(); | |||
3619 | if (!InitExpr) | |||
3620 | continue; | |||
3621 | // In class initializers will point to the constructor. | |||
3622 | UninitializedChecker.CheckInitializer(InitExpr, Constructor, | |||
3623 | FieldInit->getAnyMember(), | |||
3624 | FieldInit->getBaseClass()); | |||
3625 | } else { | |||
3626 | UninitializedChecker.CheckInitializer(InitExpr, nullptr, | |||
3627 | FieldInit->getAnyMember(), | |||
3628 | FieldInit->getBaseClass()); | |||
3629 | } | |||
3630 | } | |||
3631 | } | |||
3632 | } // namespace | |||
3633 | ||||
3634 | /// Enter a new C++ default initializer scope. After calling this, the | |||
3635 | /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if | |||
3636 | /// parsing or instantiating the initializer failed. | |||
3637 | void Sema::ActOnStartCXXInClassMemberInitializer() { | |||
3638 | // Create a synthetic function scope to represent the call to the constructor | |||
3639 | // that notionally surrounds a use of this initializer. | |||
3640 | PushFunctionScope(); | |||
3641 | } | |||
3642 | ||||
3643 | /// This is invoked after parsing an in-class initializer for a | |||
3644 | /// non-static C++ class member, and after instantiating an in-class initializer | |||
3645 | /// in a class template. Such actions are deferred until the class is complete. | |||
3646 | void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, | |||
3647 | SourceLocation InitLoc, | |||
3648 | Expr *InitExpr) { | |||
3649 | // Pop the notional constructor scope we created earlier. | |||
3650 | PopFunctionScopeInfo(nullptr, D); | |||
3651 | ||||
3652 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | |||
3653 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3654, __PRETTY_FUNCTION__)) | |||
3654 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3654, __PRETTY_FUNCTION__)); | |||
3655 | ||||
3656 | if (!InitExpr) { | |||
3657 | D->setInvalidDecl(); | |||
3658 | if (FD) | |||
3659 | FD->removeInClassInitializer(); | |||
3660 | return; | |||
3661 | } | |||
3662 | ||||
3663 | if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { | |||
3664 | FD->setInvalidDecl(); | |||
3665 | FD->removeInClassInitializer(); | |||
3666 | return; | |||
3667 | } | |||
3668 | ||||
3669 | ExprResult Init = InitExpr; | |||
3670 | if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { | |||
3671 | InitializedEntity Entity = | |||
3672 | InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); | |||
3673 | InitializationKind Kind = | |||
3674 | FD->getInClassInitStyle() == ICIS_ListInit | |||
3675 | ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), | |||
3676 | InitExpr->getBeginLoc(), | |||
3677 | InitExpr->getEndLoc()) | |||
3678 | : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); | |||
3679 | InitializationSequence Seq(*this, Entity, Kind, InitExpr); | |||
3680 | Init = Seq.Perform(*this, Entity, Kind, InitExpr); | |||
3681 | if (Init.isInvalid()) { | |||
3682 | FD->setInvalidDecl(); | |||
3683 | return; | |||
3684 | } | |||
3685 | } | |||
3686 | ||||
3687 | // C++11 [class.base.init]p7: | |||
3688 | // The initialization of each base and member constitutes a | |||
3689 | // full-expression. | |||
3690 | Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); | |||
3691 | if (Init.isInvalid()) { | |||
3692 | FD->setInvalidDecl(); | |||
3693 | return; | |||
3694 | } | |||
3695 | ||||
3696 | InitExpr = Init.get(); | |||
3697 | ||||
3698 | FD->setInClassInitializer(InitExpr); | |||
3699 | } | |||
3700 | ||||
3701 | /// Find the direct and/or virtual base specifiers that | |||
3702 | /// correspond to the given base type, for use in base initialization | |||
3703 | /// within a constructor. | |||
3704 | static bool FindBaseInitializer(Sema &SemaRef, | |||
3705 | CXXRecordDecl *ClassDecl, | |||
3706 | QualType BaseType, | |||
3707 | const CXXBaseSpecifier *&DirectBaseSpec, | |||
3708 | const CXXBaseSpecifier *&VirtualBaseSpec) { | |||
3709 | // First, check for a direct base class. | |||
3710 | DirectBaseSpec = nullptr; | |||
3711 | for (const auto &Base : ClassDecl->bases()) { | |||
3712 | if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { | |||
3713 | // We found a direct base of this type. That's what we're | |||
3714 | // initializing. | |||
3715 | DirectBaseSpec = &Base; | |||
3716 | break; | |||
3717 | } | |||
3718 | } | |||
3719 | ||||
3720 | // Check for a virtual base class. | |||
3721 | // FIXME: We might be able to short-circuit this if we know in advance that | |||
3722 | // there are no virtual bases. | |||
3723 | VirtualBaseSpec = nullptr; | |||
3724 | if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { | |||
3725 | // We haven't found a base yet; search the class hierarchy for a | |||
3726 | // virtual base class. | |||
3727 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
3728 | /*DetectVirtual=*/false); | |||
3729 | if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), | |||
3730 | SemaRef.Context.getTypeDeclType(ClassDecl), | |||
3731 | BaseType, Paths)) { | |||
3732 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); | |||
3733 | Path != Paths.end(); ++Path) { | |||
3734 | if (Path->back().Base->isVirtual()) { | |||
3735 | VirtualBaseSpec = Path->back().Base; | |||
3736 | break; | |||
3737 | } | |||
3738 | } | |||
3739 | } | |||
3740 | } | |||
3741 | ||||
3742 | return DirectBaseSpec || VirtualBaseSpec; | |||
3743 | } | |||
3744 | ||||
3745 | /// Handle a C++ member initializer using braced-init-list syntax. | |||
3746 | MemInitResult | |||
3747 | Sema::ActOnMemInitializer(Decl *ConstructorD, | |||
3748 | Scope *S, | |||
3749 | CXXScopeSpec &SS, | |||
3750 | IdentifierInfo *MemberOrBase, | |||
3751 | ParsedType TemplateTypeTy, | |||
3752 | const DeclSpec &DS, | |||
3753 | SourceLocation IdLoc, | |||
3754 | Expr *InitList, | |||
3755 | SourceLocation EllipsisLoc) { | |||
3756 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | |||
3757 | DS, IdLoc, InitList, | |||
3758 | EllipsisLoc); | |||
3759 | } | |||
3760 | ||||
3761 | /// Handle a C++ member initializer using parentheses syntax. | |||
3762 | MemInitResult | |||
3763 | Sema::ActOnMemInitializer(Decl *ConstructorD, | |||
3764 | Scope *S, | |||
3765 | CXXScopeSpec &SS, | |||
3766 | IdentifierInfo *MemberOrBase, | |||
3767 | ParsedType TemplateTypeTy, | |||
3768 | const DeclSpec &DS, | |||
3769 | SourceLocation IdLoc, | |||
3770 | SourceLocation LParenLoc, | |||
3771 | ArrayRef<Expr *> Args, | |||
3772 | SourceLocation RParenLoc, | |||
3773 | SourceLocation EllipsisLoc) { | |||
3774 | Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); | |||
3775 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | |||
3776 | DS, IdLoc, List, EllipsisLoc); | |||
3777 | } | |||
3778 | ||||
3779 | namespace { | |||
3780 | ||||
3781 | // Callback to only accept typo corrections that can be a valid C++ member | |||
3782 | // intializer: either a non-static field member or a base class. | |||
3783 | class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { | |||
3784 | public: | |||
3785 | explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) | |||
3786 | : ClassDecl(ClassDecl) {} | |||
3787 | ||||
3788 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
3789 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | |||
3790 | if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) | |||
3791 | return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); | |||
3792 | return isa<TypeDecl>(ND); | |||
3793 | } | |||
3794 | return false; | |||
3795 | } | |||
3796 | ||||
3797 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
3798 | return llvm::make_unique<MemInitializerValidatorCCC>(*this); | |||
3799 | } | |||
3800 | ||||
3801 | private: | |||
3802 | CXXRecordDecl *ClassDecl; | |||
3803 | }; | |||
3804 | ||||
3805 | } | |||
3806 | ||||
3807 | ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, | |||
3808 | CXXScopeSpec &SS, | |||
3809 | ParsedType TemplateTypeTy, | |||
3810 | IdentifierInfo *MemberOrBase) { | |||
3811 | if (SS.getScopeRep() || TemplateTypeTy) | |||
3812 | return nullptr; | |||
3813 | DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); | |||
3814 | if (Result.empty()) | |||
3815 | return nullptr; | |||
3816 | ValueDecl *Member; | |||
3817 | if ((Member = dyn_cast<FieldDecl>(Result.front())) || | |||
3818 | (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) | |||
3819 | return Member; | |||
3820 | return nullptr; | |||
3821 | } | |||
3822 | ||||
3823 | /// Handle a C++ member initializer. | |||
3824 | MemInitResult | |||
3825 | Sema::BuildMemInitializer(Decl *ConstructorD, | |||
3826 | Scope *S, | |||
3827 | CXXScopeSpec &SS, | |||
3828 | IdentifierInfo *MemberOrBase, | |||
3829 | ParsedType TemplateTypeTy, | |||
3830 | const DeclSpec &DS, | |||
3831 | SourceLocation IdLoc, | |||
3832 | Expr *Init, | |||
3833 | SourceLocation EllipsisLoc) { | |||
3834 | ExprResult Res = CorrectDelayedTyposInExpr(Init); | |||
3835 | if (!Res.isUsable()) | |||
3836 | return true; | |||
3837 | Init = Res.get(); | |||
3838 | ||||
3839 | if (!ConstructorD) | |||
3840 | return true; | |||
3841 | ||||
3842 | AdjustDeclIfTemplate(ConstructorD); | |||
3843 | ||||
3844 | CXXConstructorDecl *Constructor | |||
3845 | = dyn_cast<CXXConstructorDecl>(ConstructorD); | |||
3846 | if (!Constructor) { | |||
3847 | // The user wrote a constructor initializer on a function that is | |||
3848 | // not a C++ constructor. Ignore the error for now, because we may | |||
3849 | // have more member initializers coming; we'll diagnose it just | |||
3850 | // once in ActOnMemInitializers. | |||
3851 | return true; | |||
3852 | } | |||
3853 | ||||
3854 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
3855 | ||||
3856 | // C++ [class.base.init]p2: | |||
3857 | // Names in a mem-initializer-id are looked up in the scope of the | |||
3858 | // constructor's class and, if not found in that scope, are looked | |||
3859 | // up in the scope containing the constructor's definition. | |||
3860 | // [Note: if the constructor's class contains a member with the | |||
3861 | // same name as a direct or virtual base class of the class, a | |||
3862 | // mem-initializer-id naming the member or base class and composed | |||
3863 | // of a single identifier refers to the class member. A | |||
3864 | // mem-initializer-id for the hidden base class may be specified | |||
3865 | // using a qualified name. ] | |||
3866 | ||||
3867 | // Look for a member, first. | |||
3868 | if (ValueDecl *Member = tryLookupCtorInitMemberDecl( | |||
3869 | ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { | |||
3870 | if (EllipsisLoc.isValid()) | |||
3871 | Diag(EllipsisLoc, diag::err_pack_expansion_member_init) | |||
3872 | << MemberOrBase | |||
3873 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); | |||
3874 | ||||
3875 | return BuildMemberInitializer(Member, Init, IdLoc); | |||
3876 | } | |||
3877 | // It didn't name a member, so see if it names a class. | |||
3878 | QualType BaseType; | |||
3879 | TypeSourceInfo *TInfo = nullptr; | |||
3880 | ||||
3881 | if (TemplateTypeTy) { | |||
3882 | BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); | |||
3883 | if (BaseType.isNull()) | |||
3884 | return true; | |||
3885 | } else if (DS.getTypeSpecType() == TST_decltype) { | |||
3886 | BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); | |||
3887 | } else if (DS.getTypeSpecType() == TST_decltype_auto) { | |||
3888 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
3889 | return true; | |||
3890 | } else { | |||
3891 | LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); | |||
3892 | LookupParsedName(R, S, &SS); | |||
3893 | ||||
3894 | TypeDecl *TyD = R.getAsSingle<TypeDecl>(); | |||
3895 | if (!TyD) { | |||
3896 | if (R.isAmbiguous()) return true; | |||
3897 | ||||
3898 | // We don't want access-control diagnostics here. | |||
3899 | R.suppressDiagnostics(); | |||
3900 | ||||
3901 | if (SS.isSet() && isDependentScopeSpecifier(SS)) { | |||
3902 | bool NotUnknownSpecialization = false; | |||
3903 | DeclContext *DC = computeDeclContext(SS, false); | |||
3904 | if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) | |||
3905 | NotUnknownSpecialization = !Record->hasAnyDependentBases(); | |||
3906 | ||||
3907 | if (!NotUnknownSpecialization) { | |||
3908 | // When the scope specifier can refer to a member of an unknown | |||
3909 | // specialization, we take it as a type name. | |||
3910 | BaseType = CheckTypenameType(ETK_None, SourceLocation(), | |||
3911 | SS.getWithLocInContext(Context), | |||
3912 | *MemberOrBase, IdLoc); | |||
3913 | if (BaseType.isNull()) | |||
3914 | return true; | |||
3915 | ||||
3916 | TInfo = Context.CreateTypeSourceInfo(BaseType); | |||
3917 | DependentNameTypeLoc TL = | |||
3918 | TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); | |||
3919 | if (!TL.isNull()) { | |||
3920 | TL.setNameLoc(IdLoc); | |||
3921 | TL.setElaboratedKeywordLoc(SourceLocation()); | |||
3922 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
3923 | } | |||
3924 | ||||
3925 | R.clear(); | |||
3926 | R.setLookupName(MemberOrBase); | |||
3927 | } | |||
3928 | } | |||
3929 | ||||
3930 | // If no results were found, try to correct typos. | |||
3931 | TypoCorrection Corr; | |||
3932 | MemInitializerValidatorCCC CCC(ClassDecl); | |||
3933 | if (R.empty() && BaseType.isNull() && | |||
3934 | (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, | |||
3935 | CCC, CTK_ErrorRecovery, ClassDecl))) { | |||
3936 | if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { | |||
3937 | // We have found a non-static data member with a similar | |||
3938 | // name to what was typed; complain and initialize that | |||
3939 | // member. | |||
3940 | diagnoseTypo(Corr, | |||
3941 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | |||
3942 | << MemberOrBase << true); | |||
3943 | return BuildMemberInitializer(Member, Init, IdLoc); | |||
3944 | } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { | |||
3945 | const CXXBaseSpecifier *DirectBaseSpec; | |||
3946 | const CXXBaseSpecifier *VirtualBaseSpec; | |||
3947 | if (FindBaseInitializer(*this, ClassDecl, | |||
3948 | Context.getTypeDeclType(Type), | |||
3949 | DirectBaseSpec, VirtualBaseSpec)) { | |||
3950 | // We have found a direct or virtual base class with a | |||
3951 | // similar name to what was typed; complain and initialize | |||
3952 | // that base class. | |||
3953 | diagnoseTypo(Corr, | |||
3954 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | |||
3955 | << MemberOrBase << false, | |||
3956 | PDiag() /*Suppress note, we provide our own.*/); | |||
3957 | ||||
3958 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec | |||
3959 | : VirtualBaseSpec; | |||
3960 | Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) | |||
3961 | << BaseSpec->getType() << BaseSpec->getSourceRange(); | |||
3962 | ||||
3963 | TyD = Type; | |||
3964 | } | |||
3965 | } | |||
3966 | } | |||
3967 | ||||
3968 | if (!TyD && BaseType.isNull()) { | |||
3969 | Diag(IdLoc, diag::err_mem_init_not_member_or_class) | |||
3970 | << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); | |||
3971 | return true; | |||
3972 | } | |||
3973 | } | |||
3974 | ||||
3975 | if (BaseType.isNull()) { | |||
3976 | BaseType = Context.getTypeDeclType(TyD); | |||
3977 | MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); | |||
3978 | if (SS.isSet()) { | |||
3979 | BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), | |||
3980 | BaseType); | |||
3981 | TInfo = Context.CreateTypeSourceInfo(BaseType); | |||
3982 | ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); | |||
3983 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); | |||
3984 | TL.setElaboratedKeywordLoc(SourceLocation()); | |||
3985 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
3986 | } | |||
3987 | } | |||
3988 | } | |||
3989 | ||||
3990 | if (!TInfo) | |||
3991 | TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); | |||
3992 | ||||
3993 | return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); | |||
3994 | } | |||
3995 | ||||
3996 | MemInitResult | |||
3997 | Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, | |||
3998 | SourceLocation IdLoc) { | |||
3999 | FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); | |||
4000 | IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); | |||
4001 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4002, __PRETTY_FUNCTION__)) | |||
4002 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4002, __PRETTY_FUNCTION__)); | |||
4003 | ||||
4004 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | |||
4005 | return true; | |||
4006 | ||||
4007 | if (Member->isInvalidDecl()) | |||
4008 | return true; | |||
4009 | ||||
4010 | MultiExprArg Args; | |||
4011 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4012 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4013 | } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { | |||
4014 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | |||
4015 | } else { | |||
4016 | // Template instantiation doesn't reconstruct ParenListExprs for us. | |||
4017 | Args = Init; | |||
4018 | } | |||
4019 | ||||
4020 | SourceRange InitRange = Init->getSourceRange(); | |||
4021 | ||||
4022 | if (Member->getType()->isDependentType() || Init->isTypeDependent()) { | |||
4023 | // Can't check initialization for a member of dependent type or when | |||
4024 | // any of the arguments are type-dependent expressions. | |||
4025 | DiscardCleanupsInEvaluationContext(); | |||
4026 | } else { | |||
4027 | bool InitList = false; | |||
4028 | if (isa<InitListExpr>(Init)) { | |||
4029 | InitList = true; | |||
4030 | Args = Init; | |||
4031 | } | |||
4032 | ||||
4033 | // Initialize the member. | |||
4034 | InitializedEntity MemberEntity = | |||
4035 | DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) | |||
4036 | : InitializedEntity::InitializeMember(IndirectMember, | |||
4037 | nullptr); | |||
4038 | InitializationKind Kind = | |||
4039 | InitList ? InitializationKind::CreateDirectList( | |||
4040 | IdLoc, Init->getBeginLoc(), Init->getEndLoc()) | |||
4041 | : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), | |||
4042 | InitRange.getEnd()); | |||
4043 | ||||
4044 | InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); | |||
4045 | ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, | |||
4046 | nullptr); | |||
4047 | if (MemberInit.isInvalid()) | |||
4048 | return true; | |||
4049 | ||||
4050 | // C++11 [class.base.init]p7: | |||
4051 | // The initialization of each base and member constitutes a | |||
4052 | // full-expression. | |||
4053 | MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), | |||
4054 | /*DiscardedValue*/ false); | |||
4055 | if (MemberInit.isInvalid()) | |||
4056 | return true; | |||
4057 | ||||
4058 | Init = MemberInit.get(); | |||
4059 | } | |||
4060 | ||||
4061 | if (DirectMember) { | |||
4062 | return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, | |||
4063 | InitRange.getBegin(), Init, | |||
4064 | InitRange.getEnd()); | |||
4065 | } else { | |||
4066 | return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, | |||
4067 | InitRange.getBegin(), Init, | |||
4068 | InitRange.getEnd()); | |||
4069 | } | |||
4070 | } | |||
4071 | ||||
4072 | MemInitResult | |||
4073 | Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, | |||
4074 | CXXRecordDecl *ClassDecl) { | |||
4075 | SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
4076 | if (!LangOpts.CPlusPlus11) | |||
4077 | return Diag(NameLoc, diag::err_delegating_ctor) | |||
4078 | << TInfo->getTypeLoc().getLocalSourceRange(); | |||
4079 | Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); | |||
4080 | ||||
4081 | bool InitList = true; | |||
4082 | MultiExprArg Args = Init; | |||
4083 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4084 | InitList = false; | |||
4085 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4086 | } | |||
4087 | ||||
4088 | SourceRange InitRange = Init->getSourceRange(); | |||
4089 | // Initialize the object. | |||
4090 | InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( | |||
4091 | QualType(ClassDecl->getTypeForDecl(), 0)); | |||
4092 | InitializationKind Kind = | |||
4093 | InitList ? InitializationKind::CreateDirectList( | |||
4094 | NameLoc, Init->getBeginLoc(), Init->getEndLoc()) | |||
4095 | : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), | |||
4096 | InitRange.getEnd()); | |||
4097 | InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); | |||
4098 | ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, | |||
4099 | Args, nullptr); | |||
4100 | if (DelegationInit.isInvalid()) | |||
4101 | return true; | |||
4102 | ||||
4103 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4104, __PRETTY_FUNCTION__)) | |||
4104 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4104, __PRETTY_FUNCTION__)); | |||
4105 | ||||
4106 | // C++11 [class.base.init]p7: | |||
4107 | // The initialization of each base and member constitutes a | |||
4108 | // full-expression. | |||
4109 | DelegationInit = ActOnFinishFullExpr( | |||
4110 | DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); | |||
4111 | if (DelegationInit.isInvalid()) | |||
4112 | return true; | |||
4113 | ||||
4114 | // If we are in a dependent context, template instantiation will | |||
4115 | // perform this type-checking again. Just save the arguments that we | |||
4116 | // received in a ParenListExpr. | |||
4117 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | |||
4118 | // of the information that we have about the base | |||
4119 | // initializer. However, deconstructing the ASTs is a dicey process, | |||
4120 | // and this approach is far more likely to get the corner cases right. | |||
4121 | if (CurContext->isDependentContext()) | |||
4122 | DelegationInit = Init; | |||
4123 | ||||
4124 | return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), | |||
4125 | DelegationInit.getAs<Expr>(), | |||
4126 | InitRange.getEnd()); | |||
4127 | } | |||
4128 | ||||
4129 | MemInitResult | |||
4130 | Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, | |||
4131 | Expr *Init, CXXRecordDecl *ClassDecl, | |||
4132 | SourceLocation EllipsisLoc) { | |||
4133 | SourceLocation BaseLoc | |||
4134 | = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
4135 | ||||
4136 | if (!BaseType->isDependentType() && !BaseType->isRecordType()) | |||
4137 | return Diag(BaseLoc, diag::err_base_init_does_not_name_class) | |||
4138 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4139 | ||||
4140 | // C++ [class.base.init]p2: | |||
4141 | // [...] Unless the mem-initializer-id names a nonstatic data | |||
4142 | // member of the constructor's class or a direct or virtual base | |||
4143 | // of that class, the mem-initializer is ill-formed. A | |||
4144 | // mem-initializer-list can initialize a base class using any | |||
4145 | // name that denotes that base class type. | |||
4146 | bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); | |||
4147 | ||||
4148 | SourceRange InitRange = Init->getSourceRange(); | |||
4149 | if (EllipsisLoc.isValid()) { | |||
4150 | // This is a pack expansion. | |||
4151 | if (!BaseType->containsUnexpandedParameterPack()) { | |||
4152 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
4153 | << SourceRange(BaseLoc, InitRange.getEnd()); | |||
4154 | ||||
4155 | EllipsisLoc = SourceLocation(); | |||
4156 | } | |||
4157 | } else { | |||
4158 | // Check for any unexpanded parameter packs. | |||
4159 | if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) | |||
4160 | return true; | |||
4161 | ||||
4162 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | |||
4163 | return true; | |||
4164 | } | |||
4165 | ||||
4166 | // Check for direct and virtual base classes. | |||
4167 | const CXXBaseSpecifier *DirectBaseSpec = nullptr; | |||
4168 | const CXXBaseSpecifier *VirtualBaseSpec = nullptr; | |||
4169 | if (!Dependent) { | |||
4170 | if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), | |||
4171 | BaseType)) | |||
4172 | return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); | |||
4173 | ||||
4174 | FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, | |||
4175 | VirtualBaseSpec); | |||
4176 | ||||
4177 | // C++ [base.class.init]p2: | |||
4178 | // Unless the mem-initializer-id names a nonstatic data member of the | |||
4179 | // constructor's class or a direct or virtual base of that class, the | |||
4180 | // mem-initializer is ill-formed. | |||
4181 | if (!DirectBaseSpec && !VirtualBaseSpec) { | |||
4182 | // If the class has any dependent bases, then it's possible that | |||
4183 | // one of those types will resolve to the same type as | |||
4184 | // BaseType. Therefore, just treat this as a dependent base | |||
4185 | // class initialization. FIXME: Should we try to check the | |||
4186 | // initialization anyway? It seems odd. | |||
4187 | if (ClassDecl->hasAnyDependentBases()) | |||
4188 | Dependent = true; | |||
4189 | else | |||
4190 | return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) | |||
4191 | << BaseType << Context.getTypeDeclType(ClassDecl) | |||
4192 | << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4193 | } | |||
4194 | } | |||
4195 | ||||
4196 | if (Dependent) { | |||
4197 | DiscardCleanupsInEvaluationContext(); | |||
4198 | ||||
4199 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | |||
4200 | /*IsVirtual=*/false, | |||
4201 | InitRange.getBegin(), Init, | |||
4202 | InitRange.getEnd(), EllipsisLoc); | |||
4203 | } | |||
4204 | ||||
4205 | // C++ [base.class.init]p2: | |||
4206 | // If a mem-initializer-id is ambiguous because it designates both | |||
4207 | // a direct non-virtual base class and an inherited virtual base | |||
4208 | // class, the mem-initializer is ill-formed. | |||
4209 | if (DirectBaseSpec && VirtualBaseSpec) | |||
4210 | return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) | |||
4211 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4212 | ||||
4213 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; | |||
4214 | if (!BaseSpec) | |||
4215 | BaseSpec = VirtualBaseSpec; | |||
4216 | ||||
4217 | // Initialize the base. | |||
4218 | bool InitList = true; | |||
4219 | MultiExprArg Args = Init; | |||
4220 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4221 | InitList = false; | |||
4222 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4223 | } | |||
4224 | ||||
4225 | InitializedEntity BaseEntity = | |||
4226 | InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); | |||
4227 | InitializationKind Kind = | |||
4228 | InitList ? InitializationKind::CreateDirectList(BaseLoc) | |||
4229 | : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), | |||
4230 | InitRange.getEnd()); | |||
4231 | InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); | |||
4232 | ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); | |||
4233 | if (BaseInit.isInvalid()) | |||
4234 | return true; | |||
4235 | ||||
4236 | // C++11 [class.base.init]p7: | |||
4237 | // The initialization of each base and member constitutes a | |||
4238 | // full-expression. | |||
4239 | BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), | |||
4240 | /*DiscardedValue*/ false); | |||
4241 | if (BaseInit.isInvalid()) | |||
4242 | return true; | |||
4243 | ||||
4244 | // If we are in a dependent context, template instantiation will | |||
4245 | // perform this type-checking again. Just save the arguments that we | |||
4246 | // received in a ParenListExpr. | |||
4247 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | |||
4248 | // of the information that we have about the base | |||
4249 | // initializer. However, deconstructing the ASTs is a dicey process, | |||
4250 | // and this approach is far more likely to get the corner cases right. | |||
4251 | if (CurContext->isDependentContext()) | |||
4252 | BaseInit = Init; | |||
4253 | ||||
4254 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | |||
4255 | BaseSpec->isVirtual(), | |||
4256 | InitRange.getBegin(), | |||
4257 | BaseInit.getAs<Expr>(), | |||
4258 | InitRange.getEnd(), EllipsisLoc); | |||
4259 | } | |||
4260 | ||||
4261 | // Create a static_cast\<T&&>(expr). | |||
4262 | static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { | |||
4263 | if (T.isNull()) T = E->getType(); | |||
4264 | QualType TargetType = SemaRef.BuildReferenceType( | |||
4265 | T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); | |||
4266 | SourceLocation ExprLoc = E->getBeginLoc(); | |||
4267 | TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( | |||
4268 | TargetType, ExprLoc); | |||
4269 | ||||
4270 | return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, | |||
4271 | SourceRange(ExprLoc, ExprLoc), | |||
4272 | E->getSourceRange()).get(); | |||
4273 | } | |||
4274 | ||||
4275 | /// ImplicitInitializerKind - How an implicit base or member initializer should | |||
4276 | /// initialize its base or member. | |||
4277 | enum ImplicitInitializerKind { | |||
4278 | IIK_Default, | |||
4279 | IIK_Copy, | |||
4280 | IIK_Move, | |||
4281 | IIK_Inherit | |||
4282 | }; | |||
4283 | ||||
4284 | static bool | |||
4285 | BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | |||
4286 | ImplicitInitializerKind ImplicitInitKind, | |||
4287 | CXXBaseSpecifier *BaseSpec, | |||
4288 | bool IsInheritedVirtualBase, | |||
4289 | CXXCtorInitializer *&CXXBaseInit) { | |||
4290 | InitializedEntity InitEntity | |||
4291 | = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, | |||
4292 | IsInheritedVirtualBase); | |||
4293 | ||||
4294 | ExprResult BaseInit; | |||
4295 | ||||
4296 | switch (ImplicitInitKind) { | |||
4297 | case IIK_Inherit: | |||
4298 | case IIK_Default: { | |||
4299 | InitializationKind InitKind | |||
4300 | = InitializationKind::CreateDefault(Constructor->getLocation()); | |||
4301 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | |||
4302 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | |||
4303 | break; | |||
4304 | } | |||
4305 | ||||
4306 | case IIK_Move: | |||
4307 | case IIK_Copy: { | |||
4308 | bool Moving = ImplicitInitKind == IIK_Move; | |||
4309 | ParmVarDecl *Param = Constructor->getParamDecl(0); | |||
4310 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
4311 | ||||
4312 | Expr *CopyCtorArg = | |||
4313 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | |||
4314 | SourceLocation(), Param, false, | |||
4315 | Constructor->getLocation(), ParamType, | |||
4316 | VK_LValue, nullptr); | |||
4317 | ||||
4318 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); | |||
4319 | ||||
4320 | // Cast to the base class to avoid ambiguities. | |||
4321 | QualType ArgTy = | |||
4322 | SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), | |||
4323 | ParamType.getQualifiers()); | |||
4324 | ||||
4325 | if (Moving) { | |||
4326 | CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); | |||
4327 | } | |||
4328 | ||||
4329 | CXXCastPath BasePath; | |||
4330 | BasePath.push_back(BaseSpec); | |||
4331 | CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, | |||
4332 | CK_UncheckedDerivedToBase, | |||
4333 | Moving ? VK_XValue : VK_LValue, | |||
4334 | &BasePath).get(); | |||
4335 | ||||
4336 | InitializationKind InitKind | |||
4337 | = InitializationKind::CreateDirect(Constructor->getLocation(), | |||
4338 | SourceLocation(), SourceLocation()); | |||
4339 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); | |||
4340 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); | |||
4341 | break; | |||
4342 | } | |||
4343 | } | |||
4344 | ||||
4345 | BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); | |||
4346 | if (BaseInit.isInvalid()) | |||
4347 | return true; | |||
4348 | ||||
4349 | CXXBaseInit = | |||
4350 | new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4351 | SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), | |||
4352 | SourceLocation()), | |||
4353 | BaseSpec->isVirtual(), | |||
4354 | SourceLocation(), | |||
4355 | BaseInit.getAs<Expr>(), | |||
4356 | SourceLocation(), | |||
4357 | SourceLocation()); | |||
4358 | ||||
4359 | return false; | |||
4360 | } | |||
4361 | ||||
4362 | static bool RefersToRValueRef(Expr *MemRef) { | |||
4363 | ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); | |||
4364 | return Referenced->getType()->isRValueReferenceType(); | |||
4365 | } | |||
4366 | ||||
4367 | static bool | |||
4368 | BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | |||
4369 | ImplicitInitializerKind ImplicitInitKind, | |||
4370 | FieldDecl *Field, IndirectFieldDecl *Indirect, | |||
4371 | CXXCtorInitializer *&CXXMemberInit) { | |||
4372 | if (Field->isInvalidDecl()) | |||
4373 | return true; | |||
4374 | ||||
4375 | SourceLocation Loc = Constructor->getLocation(); | |||
4376 | ||||
4377 | if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { | |||
4378 | bool Moving = ImplicitInitKind == IIK_Move; | |||
4379 | ParmVarDecl *Param = Constructor->getParamDecl(0); | |||
4380 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
4381 | ||||
4382 | // Suppress copying zero-width bitfields. | |||
4383 | if (Field->isZeroLengthBitField(SemaRef.Context)) | |||
4384 | return false; | |||
4385 | ||||
4386 | Expr *MemberExprBase = | |||
4387 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | |||
4388 | SourceLocation(), Param, false, | |||
4389 | Loc, ParamType, VK_LValue, nullptr); | |||
4390 | ||||
4391 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); | |||
4392 | ||||
4393 | if (Moving) { | |||
4394 | MemberExprBase = CastForMoving(SemaRef, MemberExprBase); | |||
4395 | } | |||
4396 | ||||
4397 | // Build a reference to this field within the parameter. | |||
4398 | CXXScopeSpec SS; | |||
4399 | LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, | |||
4400 | Sema::LookupMemberName); | |||
4401 | MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) | |||
4402 | : cast<ValueDecl>(Field), AS_public); | |||
4403 | MemberLookup.resolveKind(); | |||
4404 | ExprResult CtorArg | |||
4405 | = SemaRef.BuildMemberReferenceExpr(MemberExprBase, | |||
4406 | ParamType, Loc, | |||
4407 | /*IsArrow=*/false, | |||
4408 | SS, | |||
4409 | /*TemplateKWLoc=*/SourceLocation(), | |||
4410 | /*FirstQualifierInScope=*/nullptr, | |||
4411 | MemberLookup, | |||
4412 | /*TemplateArgs=*/nullptr, | |||
4413 | /*S*/nullptr); | |||
4414 | if (CtorArg.isInvalid()) | |||
4415 | return true; | |||
4416 | ||||
4417 | // C++11 [class.copy]p15: | |||
4418 | // - if a member m has rvalue reference type T&&, it is direct-initialized | |||
4419 | // with static_cast<T&&>(x.m); | |||
4420 | if (RefersToRValueRef(CtorArg.get())) { | |||
4421 | CtorArg = CastForMoving(SemaRef, CtorArg.get()); | |||
4422 | } | |||
4423 | ||||
4424 | InitializedEntity Entity = | |||
4425 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | |||
4426 | /*Implicit*/ true) | |||
4427 | : InitializedEntity::InitializeMember(Field, nullptr, | |||
4428 | /*Implicit*/ true); | |||
4429 | ||||
4430 | // Direct-initialize to use the copy constructor. | |||
4431 | InitializationKind InitKind = | |||
4432 | InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); | |||
4433 | ||||
4434 | Expr *CtorArgE = CtorArg.getAs<Expr>(); | |||
4435 | InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); | |||
4436 | ExprResult MemberInit = | |||
4437 | InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); | |||
4438 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | |||
4439 | if (MemberInit.isInvalid()) | |||
4440 | return true; | |||
4441 | ||||
4442 | if (Indirect) | |||
4443 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | |||
4444 | SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | |||
4445 | else | |||
4446 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | |||
4447 | SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | |||
4448 | return false; | |||
4449 | } | |||
4450 | ||||
4451 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4452, __PRETTY_FUNCTION__)) | |||
4452 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4452, __PRETTY_FUNCTION__)); | |||
4453 | ||||
4454 | QualType FieldBaseElementType = | |||
4455 | SemaRef.Context.getBaseElementType(Field->getType()); | |||
4456 | ||||
4457 | if (FieldBaseElementType->isRecordType()) { | |||
4458 | InitializedEntity InitEntity = | |||
4459 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | |||
4460 | /*Implicit*/ true) | |||
4461 | : InitializedEntity::InitializeMember(Field, nullptr, | |||
4462 | /*Implicit*/ true); | |||
4463 | InitializationKind InitKind = | |||
4464 | InitializationKind::CreateDefault(Loc); | |||
4465 | ||||
4466 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | |||
4467 | ExprResult MemberInit = | |||
4468 | InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | |||
4469 | ||||
4470 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | |||
4471 | if (MemberInit.isInvalid()) | |||
4472 | return true; | |||
4473 | ||||
4474 | if (Indirect) | |||
4475 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4476 | Indirect, Loc, | |||
4477 | Loc, | |||
4478 | MemberInit.get(), | |||
4479 | Loc); | |||
4480 | else | |||
4481 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4482 | Field, Loc, Loc, | |||
4483 | MemberInit.get(), | |||
4484 | Loc); | |||
4485 | return false; | |||
4486 | } | |||
4487 | ||||
4488 | if (!Field->getParent()->isUnion()) { | |||
4489 | if (FieldBaseElementType->isReferenceType()) { | |||
4490 | SemaRef.Diag(Constructor->getLocation(), | |||
4491 | diag::err_uninitialized_member_in_ctor) | |||
4492 | << (int)Constructor->isImplicit() | |||
4493 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | |||
4494 | << 0 << Field->getDeclName(); | |||
4495 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | |||
4496 | return true; | |||
4497 | } | |||
4498 | ||||
4499 | if (FieldBaseElementType.isConstQualified()) { | |||
4500 | SemaRef.Diag(Constructor->getLocation(), | |||
4501 | diag::err_uninitialized_member_in_ctor) | |||
4502 | << (int)Constructor->isImplicit() | |||
4503 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | |||
4504 | << 1 << Field->getDeclName(); | |||
4505 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | |||
4506 | return true; | |||
4507 | } | |||
4508 | } | |||
4509 | ||||
4510 | if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { | |||
4511 | // ARC and Weak: | |||
4512 | // Default-initialize Objective-C pointers to NULL. | |||
4513 | CXXMemberInit | |||
4514 | = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, | |||
4515 | Loc, Loc, | |||
4516 | new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), | |||
4517 | Loc); | |||
4518 | return false; | |||
4519 | } | |||
4520 | ||||
4521 | // Nothing to initialize. | |||
4522 | CXXMemberInit = nullptr; | |||
4523 | return false; | |||
4524 | } | |||
4525 | ||||
4526 | namespace { | |||
4527 | struct BaseAndFieldInfo { | |||
4528 | Sema &S; | |||
4529 | CXXConstructorDecl *Ctor; | |||
4530 | bool AnyErrorsInInits; | |||
4531 | ImplicitInitializerKind IIK; | |||
4532 | llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; | |||
4533 | SmallVector<CXXCtorInitializer*, 8> AllToInit; | |||
4534 | llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; | |||
4535 | ||||
4536 | BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) | |||
4537 | : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { | |||
4538 | bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); | |||
4539 | if (Ctor->getInheritedConstructor()) | |||
4540 | IIK = IIK_Inherit; | |||
4541 | else if (Generated && Ctor->isCopyConstructor()) | |||
4542 | IIK = IIK_Copy; | |||
4543 | else if (Generated && Ctor->isMoveConstructor()) | |||
4544 | IIK = IIK_Move; | |||
4545 | else | |||
4546 | IIK = IIK_Default; | |||
4547 | } | |||
4548 | ||||
4549 | bool isImplicitCopyOrMove() const { | |||
4550 | switch (IIK) { | |||
4551 | case IIK_Copy: | |||
4552 | case IIK_Move: | |||
4553 | return true; | |||
4554 | ||||
4555 | case IIK_Default: | |||
4556 | case IIK_Inherit: | |||
4557 | return false; | |||
4558 | } | |||
4559 | ||||
4560 | llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4560); | |||
4561 | } | |||
4562 | ||||
4563 | bool addFieldInitializer(CXXCtorInitializer *Init) { | |||
4564 | AllToInit.push_back(Init); | |||
4565 | ||||
4566 | // Check whether this initializer makes the field "used". | |||
4567 | if (Init->getInit()->HasSideEffects(S.Context)) | |||
4568 | S.UnusedPrivateFields.remove(Init->getAnyMember()); | |||
4569 | ||||
4570 | return false; | |||
4571 | } | |||
4572 | ||||
4573 | bool isInactiveUnionMember(FieldDecl *Field) { | |||
4574 | RecordDecl *Record = Field->getParent(); | |||
4575 | if (!Record->isUnion()) | |||
4576 | return false; | |||
4577 | ||||
4578 | if (FieldDecl *Active = | |||
4579 | ActiveUnionMember.lookup(Record->getCanonicalDecl())) | |||
4580 | return Active != Field->getCanonicalDecl(); | |||
4581 | ||||
4582 | // In an implicit copy or move constructor, ignore any in-class initializer. | |||
4583 | if (isImplicitCopyOrMove()) | |||
4584 | return true; | |||
4585 | ||||
4586 | // If there's no explicit initialization, the field is active only if it | |||
4587 | // has an in-class initializer... | |||
4588 | if (Field->hasInClassInitializer()) | |||
4589 | return false; | |||
4590 | // ... or it's an anonymous struct or union whose class has an in-class | |||
4591 | // initializer. | |||
4592 | if (!Field->isAnonymousStructOrUnion()) | |||
4593 | return true; | |||
4594 | CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); | |||
4595 | return !FieldRD->hasInClassInitializer(); | |||
4596 | } | |||
4597 | ||||
4598 | /// Determine whether the given field is, or is within, a union member | |||
4599 | /// that is inactive (because there was an initializer given for a different | |||
4600 | /// member of the union, or because the union was not initialized at all). | |||
4601 | bool isWithinInactiveUnionMember(FieldDecl *Field, | |||
4602 | IndirectFieldDecl *Indirect) { | |||
4603 | if (!Indirect) | |||
4604 | return isInactiveUnionMember(Field); | |||
4605 | ||||
4606 | for (auto *C : Indirect->chain()) { | |||
4607 | FieldDecl *Field = dyn_cast<FieldDecl>(C); | |||
4608 | if (Field && isInactiveUnionMember(Field)) | |||
4609 | return true; | |||
4610 | } | |||
4611 | return false; | |||
4612 | } | |||
4613 | }; | |||
4614 | } | |||
4615 | ||||
4616 | /// Determine whether the given type is an incomplete or zero-lenfgth | |||
4617 | /// array type. | |||
4618 | static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { | |||
4619 | if (T->isIncompleteArrayType()) | |||
4620 | return true; | |||
4621 | ||||
4622 | while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { | |||
4623 | if (!ArrayT->getSize()) | |||
4624 | return true; | |||
4625 | ||||
4626 | T = ArrayT->getElementType(); | |||
4627 | } | |||
4628 | ||||
4629 | return false; | |||
4630 | } | |||
4631 | ||||
4632 | static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, | |||
4633 | FieldDecl *Field, | |||
4634 | IndirectFieldDecl *Indirect = nullptr) { | |||
4635 | if (Field->isInvalidDecl()) | |||
4636 | return false; | |||
4637 | ||||
4638 | // Overwhelmingly common case: we have a direct initializer for this field. | |||
4639 | if (CXXCtorInitializer *Init = | |||
4640 | Info.AllBaseFields.lookup(Field->getCanonicalDecl())) | |||
4641 | return Info.addFieldInitializer(Init); | |||
4642 | ||||
4643 | // C++11 [class.base.init]p8: | |||
4644 | // if the entity is a non-static data member that has a | |||
4645 | // brace-or-equal-initializer and either | |||
4646 | // -- the constructor's class is a union and no other variant member of that | |||
4647 | // union is designated by a mem-initializer-id or | |||
4648 | // -- the constructor's class is not a union, and, if the entity is a member | |||
4649 | // of an anonymous union, no other member of that union is designated by | |||
4650 | // a mem-initializer-id, | |||
4651 | // the entity is initialized as specified in [dcl.init]. | |||
4652 | // | |||
4653 | // We also apply the same rules to handle anonymous structs within anonymous | |||
4654 | // unions. | |||
4655 | if (Info.isWithinInactiveUnionMember(Field, Indirect)) | |||
4656 | return false; | |||
4657 | ||||
4658 | if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { | |||
4659 | ExprResult DIE = | |||
4660 | SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); | |||
4661 | if (DIE.isInvalid()) | |||
4662 | return true; | |||
4663 | ||||
4664 | auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); | |||
4665 | SemaRef.checkInitializerLifetime(Entity, DIE.get()); | |||
4666 | ||||
4667 | CXXCtorInitializer *Init; | |||
4668 | if (Indirect) | |||
4669 | Init = new (SemaRef.Context) | |||
4670 | CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), | |||
4671 | SourceLocation(), DIE.get(), SourceLocation()); | |||
4672 | else | |||
4673 | Init = new (SemaRef.Context) | |||
4674 | CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), | |||
4675 | SourceLocation(), DIE.get(), SourceLocation()); | |||
4676 | return Info.addFieldInitializer(Init); | |||
4677 | } | |||
4678 | ||||
4679 | // Don't initialize incomplete or zero-length arrays. | |||
4680 | if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) | |||
4681 | return false; | |||
4682 | ||||
4683 | // Don't try to build an implicit initializer if there were semantic | |||
4684 | // errors in any of the initializers (and therefore we might be | |||
4685 | // missing some that the user actually wrote). | |||
4686 | if (Info.AnyErrorsInInits) | |||
4687 | return false; | |||
4688 | ||||
4689 | CXXCtorInitializer *Init = nullptr; | |||
4690 | if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, | |||
4691 | Indirect, Init)) | |||
4692 | return true; | |||
4693 | ||||
4694 | if (!Init) | |||
4695 | return false; | |||
4696 | ||||
4697 | return Info.addFieldInitializer(Init); | |||
4698 | } | |||
4699 | ||||
4700 | bool | |||
4701 | Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, | |||
4702 | CXXCtorInitializer *Initializer) { | |||
4703 | assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast< void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4703, __PRETTY_FUNCTION__)); | |||
4704 | Constructor->setNumCtorInitializers(1); | |||
4705 | CXXCtorInitializer **initializer = | |||
4706 | new (Context) CXXCtorInitializer*[1]; | |||
4707 | memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); | |||
4708 | Constructor->setCtorInitializers(initializer); | |||
4709 | ||||
4710 | if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { | |||
4711 | MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); | |||
4712 | DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); | |||
4713 | } | |||
4714 | ||||
4715 | DelegatingCtorDecls.push_back(Constructor); | |||
4716 | ||||
4717 | DiagnoseUninitializedFields(*this, Constructor); | |||
4718 | ||||
4719 | return false; | |||
4720 | } | |||
4721 | ||||
4722 | bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, | |||
4723 | ArrayRef<CXXCtorInitializer *> Initializers) { | |||
4724 | if (Constructor->isDependentContext()) { | |||
4725 | // Just store the initializers as written, they will be checked during | |||
4726 | // instantiation. | |||
4727 | if (!Initializers.empty()) { | |||
4728 | Constructor->setNumCtorInitializers(Initializers.size()); | |||
4729 | CXXCtorInitializer **baseOrMemberInitializers = | |||
4730 | new (Context) CXXCtorInitializer*[Initializers.size()]; | |||
4731 | memcpy(baseOrMemberInitializers, Initializers.data(), | |||
4732 | Initializers.size() * sizeof(CXXCtorInitializer*)); | |||
4733 | Constructor->setCtorInitializers(baseOrMemberInitializers); | |||
4734 | } | |||
4735 | ||||
4736 | // Let template instantiation know whether we had errors. | |||
4737 | if (AnyErrors) | |||
4738 | Constructor->setInvalidDecl(); | |||
4739 | ||||
4740 | return false; | |||
4741 | } | |||
4742 | ||||
4743 | BaseAndFieldInfo Info(*this, Constructor, AnyErrors); | |||
4744 | ||||
4745 | // We need to build the initializer AST according to order of construction | |||
4746 | // and not what user specified in the Initializers list. | |||
4747 | CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); | |||
4748 | if (!ClassDecl) | |||
4749 | return true; | |||
4750 | ||||
4751 | bool HadError = false; | |||
4752 | ||||
4753 | for (unsigned i = 0; i < Initializers.size(); i++) { | |||
4754 | CXXCtorInitializer *Member = Initializers[i]; | |||
4755 | ||||
4756 | if (Member->isBaseInitializer()) | |||
4757 | Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; | |||
4758 | else { | |||
4759 | Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; | |||
4760 | ||||
4761 | if (IndirectFieldDecl *F = Member->getIndirectMember()) { | |||
4762 | for (auto *C : F->chain()) { | |||
4763 | FieldDecl *FD = dyn_cast<FieldDecl>(C); | |||
4764 | if (FD && FD->getParent()->isUnion()) | |||
4765 | Info.ActiveUnionMember.insert(std::make_pair( | |||
4766 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | |||
4767 | } | |||
4768 | } else if (FieldDecl *FD = Member->getMember()) { | |||
4769 | if (FD->getParent()->isUnion()) | |||
4770 | Info.ActiveUnionMember.insert(std::make_pair( | |||
4771 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | |||
4772 | } | |||
4773 | } | |||
4774 | } | |||
4775 | ||||
4776 | // Keep track of the direct virtual bases. | |||
4777 | llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; | |||
4778 | for (auto &I : ClassDecl->bases()) { | |||
4779 | if (I.isVirtual()) | |||
4780 | DirectVBases.insert(&I); | |||
4781 | } | |||
4782 | ||||
4783 | // Push virtual bases before others. | |||
4784 | for (auto &VBase : ClassDecl->vbases()) { | |||
4785 | if (CXXCtorInitializer *Value | |||
4786 | = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { | |||
4787 | // [class.base.init]p7, per DR257: | |||
4788 | // A mem-initializer where the mem-initializer-id names a virtual base | |||
4789 | // class is ignored during execution of a constructor of any class that | |||
4790 | // is not the most derived class. | |||
4791 | if (ClassDecl->isAbstract()) { | |||
4792 | // FIXME: Provide a fixit to remove the base specifier. This requires | |||
4793 | // tracking the location of the associated comma for a base specifier. | |||
4794 | Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) | |||
4795 | << VBase.getType() << ClassDecl; | |||
4796 | DiagnoseAbstractType(ClassDecl); | |||
4797 | } | |||
4798 | ||||
4799 | Info.AllToInit.push_back(Value); | |||
4800 | } else if (!AnyErrors && !ClassDecl->isAbstract()) { | |||
4801 | // [class.base.init]p8, per DR257: | |||
4802 | // If a given [...] base class is not named by a mem-initializer-id | |||
4803 | // [...] and the entity is not a virtual base class of an abstract | |||
4804 | // class, then [...] the entity is default-initialized. | |||
4805 | bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); | |||
4806 | CXXCtorInitializer *CXXBaseInit; | |||
4807 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | |||
4808 | &VBase, IsInheritedVirtualBase, | |||
4809 | CXXBaseInit)) { | |||
4810 | HadError = true; | |||
4811 | continue; | |||
4812 | } | |||
4813 | ||||
4814 | Info.AllToInit.push_back(CXXBaseInit); | |||
4815 | } | |||
4816 | } | |||
4817 | ||||
4818 | // Non-virtual bases. | |||
4819 | for (auto &Base : ClassDecl->bases()) { | |||
4820 | // Virtuals are in the virtual base list and already constructed. | |||
4821 | if (Base.isVirtual()) | |||
4822 | continue; | |||
4823 | ||||
4824 | if (CXXCtorInitializer *Value | |||
4825 | = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { | |||
4826 | Info.AllToInit.push_back(Value); | |||
4827 | } else if (!AnyErrors) { | |||
4828 | CXXCtorInitializer *CXXBaseInit; | |||
4829 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | |||
4830 | &Base, /*IsInheritedVirtualBase=*/false, | |||
4831 | CXXBaseInit)) { | |||
4832 | HadError = true; | |||
4833 | continue; | |||
4834 | } | |||
4835 | ||||
4836 | Info.AllToInit.push_back(CXXBaseInit); | |||
4837 | } | |||
4838 | } | |||
4839 | ||||
4840 | // Fields. | |||
4841 | for (auto *Mem : ClassDecl->decls()) { | |||
4842 | if (auto *F = dyn_cast<FieldDecl>(Mem)) { | |||
4843 | // C++ [class.bit]p2: | |||
4844 | // A declaration for a bit-field that omits the identifier declares an | |||
4845 | // unnamed bit-field. Unnamed bit-fields are not members and cannot be | |||
4846 | // initialized. | |||
4847 | if (F->isUnnamedBitfield()) | |||
4848 | continue; | |||
4849 | ||||
4850 | // If we're not generating the implicit copy/move constructor, then we'll | |||
4851 | // handle anonymous struct/union fields based on their individual | |||
4852 | // indirect fields. | |||
4853 | if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) | |||
4854 | continue; | |||
4855 | ||||
4856 | if (CollectFieldInitializer(*this, Info, F)) | |||
4857 | HadError = true; | |||
4858 | continue; | |||
4859 | } | |||
4860 | ||||
4861 | // Beyond this point, we only consider default initialization. | |||
4862 | if (Info.isImplicitCopyOrMove()) | |||
4863 | continue; | |||
4864 | ||||
4865 | if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { | |||
4866 | if (F->getType()->isIncompleteArrayType()) { | |||
4867 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4868, __PRETTY_FUNCTION__)) | |||
4868 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4868, __PRETTY_FUNCTION__)); | |||
4869 | continue; | |||
4870 | } | |||
4871 | ||||
4872 | // Initialize each field of an anonymous struct individually. | |||
4873 | if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) | |||
4874 | HadError = true; | |||
4875 | ||||
4876 | continue; | |||
4877 | } | |||
4878 | } | |||
4879 | ||||
4880 | unsigned NumInitializers = Info.AllToInit.size(); | |||
4881 | if (NumInitializers > 0) { | |||
4882 | Constructor->setNumCtorInitializers(NumInitializers); | |||
4883 | CXXCtorInitializer **baseOrMemberInitializers = | |||
4884 | new (Context) CXXCtorInitializer*[NumInitializers]; | |||
4885 | memcpy(baseOrMemberInitializers, Info.AllToInit.data(), | |||
4886 | NumInitializers * sizeof(CXXCtorInitializer*)); | |||
4887 | Constructor->setCtorInitializers(baseOrMemberInitializers); | |||
4888 | ||||
4889 | // Constructors implicitly reference the base and member | |||
4890 | // destructors. | |||
4891 | MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), | |||
4892 | Constructor->getParent()); | |||
4893 | } | |||
4894 | ||||
4895 | return HadError; | |||
4896 | } | |||
4897 | ||||
4898 | static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { | |||
4899 | if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { | |||
4900 | const RecordDecl *RD = RT->getDecl(); | |||
4901 | if (RD->isAnonymousStructOrUnion()) { | |||
4902 | for (auto *Field : RD->fields()) | |||
4903 | PopulateKeysForFields(Field, IdealInits); | |||
4904 | return; | |||
4905 | } | |||
4906 | } | |||
4907 | IdealInits.push_back(Field->getCanonicalDecl()); | |||
4908 | } | |||
4909 | ||||
4910 | static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { | |||
4911 | return Context.getCanonicalType(BaseType).getTypePtr(); | |||
4912 | } | |||
4913 | ||||
4914 | static const void *GetKeyForMember(ASTContext &Context, | |||
4915 | CXXCtorInitializer *Member) { | |||
4916 | if (!Member->isAnyMemberInitializer()) | |||
4917 | return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); | |||
4918 | ||||
4919 | return Member->getAnyMember()->getCanonicalDecl(); | |||
4920 | } | |||
4921 | ||||
4922 | static void DiagnoseBaseOrMemInitializerOrder( | |||
4923 | Sema &SemaRef, const CXXConstructorDecl *Constructor, | |||
4924 | ArrayRef<CXXCtorInitializer *> Inits) { | |||
4925 | if (Constructor->getDeclContext()->isDependentContext()) | |||
4926 | return; | |||
4927 | ||||
4928 | // Don't check initializers order unless the warning is enabled at the | |||
4929 | // location of at least one initializer. | |||
4930 | bool ShouldCheckOrder = false; | |||
4931 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | |||
4932 | CXXCtorInitializer *Init = Inits[InitIndex]; | |||
4933 | if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, | |||
4934 | Init->getSourceLocation())) { | |||
4935 | ShouldCheckOrder = true; | |||
4936 | break; | |||
4937 | } | |||
4938 | } | |||
4939 | if (!ShouldCheckOrder) | |||
4940 | return; | |||
4941 | ||||
4942 | // Build the list of bases and members in the order that they'll | |||
4943 | // actually be initialized. The explicit initializers should be in | |||
4944 | // this same order but may be missing things. | |||
4945 | SmallVector<const void*, 32> IdealInitKeys; | |||
4946 | ||||
4947 | const CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
4948 | ||||
4949 | // 1. Virtual bases. | |||
4950 | for (const auto &VBase : ClassDecl->vbases()) | |||
4951 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); | |||
4952 | ||||
4953 | // 2. Non-virtual bases. | |||
4954 | for (const auto &Base : ClassDecl->bases()) { | |||
4955 | if (Base.isVirtual()) | |||
4956 | continue; | |||
4957 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); | |||
4958 | } | |||
4959 | ||||
4960 | // 3. Direct fields. | |||
4961 | for (auto *Field : ClassDecl->fields()) { | |||
4962 | if (Field->isUnnamedBitfield()) | |||
4963 | continue; | |||
4964 | ||||
4965 | PopulateKeysForFields(Field, IdealInitKeys); | |||
4966 | } | |||
4967 | ||||
4968 | unsigned NumIdealInits = IdealInitKeys.size(); | |||
4969 | unsigned IdealIndex = 0; | |||
4970 | ||||
4971 | CXXCtorInitializer *PrevInit = nullptr; | |||
4972 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | |||
4973 | CXXCtorInitializer *Init = Inits[InitIndex]; | |||
4974 | const void *InitKey = GetKeyForMember(SemaRef.Context, Init); | |||
4975 | ||||
4976 | // Scan forward to try to find this initializer in the idealized | |||
4977 | // initializers list. | |||
4978 | for (; IdealIndex != NumIdealInits; ++IdealIndex) | |||
4979 | if (InitKey == IdealInitKeys[IdealIndex]) | |||
4980 | break; | |||
4981 | ||||
4982 | // If we didn't find this initializer, it must be because we | |||
4983 | // scanned past it on a previous iteration. That can only | |||
4984 | // happen if we're out of order; emit a warning. | |||
4985 | if (IdealIndex == NumIdealInits && PrevInit) { | |||
4986 | Sema::SemaDiagnosticBuilder D = | |||
4987 | SemaRef.Diag(PrevInit->getSourceLocation(), | |||
4988 | diag::warn_initializer_out_of_order); | |||
4989 | ||||
4990 | if (PrevInit->isAnyMemberInitializer()) | |||
4991 | D << 0 << PrevInit->getAnyMember()->getDeclName(); | |||
4992 | else | |||
4993 | D << 1 << PrevInit->getTypeSourceInfo()->getType(); | |||
4994 | ||||
4995 | if (Init->isAnyMemberInitializer()) | |||
4996 | D << 0 << Init->getAnyMember()->getDeclName(); | |||
4997 | else | |||
4998 | D << 1 << Init->getTypeSourceInfo()->getType(); | |||
4999 | ||||
5000 | // Move back to the initializer's location in the ideal list. | |||
5001 | for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) | |||
5002 | if (InitKey == IdealInitKeys[IdealIndex]) | |||
5003 | break; | |||
5004 | ||||
5005 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5006, __PRETTY_FUNCTION__)) | |||
5006 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5006, __PRETTY_FUNCTION__)); | |||
5007 | } | |||
5008 | ||||
5009 | PrevInit = Init; | |||
5010 | } | |||
5011 | } | |||
5012 | ||||
5013 | namespace { | |||
5014 | bool CheckRedundantInit(Sema &S, | |||
5015 | CXXCtorInitializer *Init, | |||
5016 | CXXCtorInitializer *&PrevInit) { | |||
5017 | if (!PrevInit) { | |||
5018 | PrevInit = Init; | |||
5019 | return false; | |||
5020 | } | |||
5021 | ||||
5022 | if (FieldDecl *Field = Init->getAnyMember()) | |||
5023 | S.Diag(Init->getSourceLocation(), | |||
5024 | diag::err_multiple_mem_initialization) | |||
5025 | << Field->getDeclName() | |||
5026 | << Init->getSourceRange(); | |||
5027 | else { | |||
5028 | const Type *BaseClass = Init->getBaseClass(); | |||
5029 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5029, __PRETTY_FUNCTION__)); | |||
5030 | S.Diag(Init->getSourceLocation(), | |||
5031 | diag::err_multiple_base_initialization) | |||
5032 | << QualType(BaseClass, 0) | |||
5033 | << Init->getSourceRange(); | |||
5034 | } | |||
5035 | S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) | |||
5036 | << 0 << PrevInit->getSourceRange(); | |||
5037 | ||||
5038 | return true; | |||
5039 | } | |||
5040 | ||||
5041 | typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; | |||
5042 | typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; | |||
5043 | ||||
5044 | bool CheckRedundantUnionInit(Sema &S, | |||
5045 | CXXCtorInitializer *Init, | |||
5046 | RedundantUnionMap &Unions) { | |||
5047 | FieldDecl *Field = Init->getAnyMember(); | |||
5048 | RecordDecl *Parent = Field->getParent(); | |||
5049 | NamedDecl *Child = Field; | |||
5050 | ||||
5051 | while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { | |||
5052 | if (Parent->isUnion()) { | |||
5053 | UnionEntry &En = Unions[Parent]; | |||
5054 | if (En.first && En.first != Child) { | |||
5055 | S.Diag(Init->getSourceLocation(), | |||
5056 | diag::err_multiple_mem_union_initialization) | |||
5057 | << Field->getDeclName() | |||
5058 | << Init->getSourceRange(); | |||
5059 | S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) | |||
5060 | << 0 << En.second->getSourceRange(); | |||
5061 | return true; | |||
5062 | } | |||
5063 | if (!En.first) { | |||
5064 | En.first = Child; | |||
5065 | En.second = Init; | |||
5066 | } | |||
5067 | if (!Parent->isAnonymousStructOrUnion()) | |||
5068 | return false; | |||
5069 | } | |||
5070 | ||||
5071 | Child = Parent; | |||
5072 | Parent = cast<RecordDecl>(Parent->getDeclContext()); | |||
5073 | } | |||
5074 | ||||
5075 | return false; | |||
5076 | } | |||
5077 | } | |||
5078 | ||||
5079 | /// ActOnMemInitializers - Handle the member initializers for a constructor. | |||
5080 | void Sema::ActOnMemInitializers(Decl *ConstructorDecl, | |||
5081 | SourceLocation ColonLoc, | |||
5082 | ArrayRef<CXXCtorInitializer*> MemInits, | |||
5083 | bool AnyErrors) { | |||
5084 | if (!ConstructorDecl) | |||
5085 | return; | |||
5086 | ||||
5087 | AdjustDeclIfTemplate(ConstructorDecl); | |||
5088 | ||||
5089 | CXXConstructorDecl *Constructor | |||
5090 | = dyn_cast<CXXConstructorDecl>(ConstructorDecl); | |||
5091 | ||||
5092 | if (!Constructor) { | |||
5093 | Diag(ColonLoc, diag::err_only_constructors_take_base_inits); | |||
5094 | return; | |||
5095 | } | |||
5096 | ||||
5097 | // Mapping for the duplicate initializers check. | |||
5098 | // For member initializers, this is keyed with a FieldDecl*. | |||
5099 | // For base initializers, this is keyed with a Type*. | |||
5100 | llvm::DenseMap<const void *, CXXCtorInitializer *> Members; | |||
5101 | ||||
5102 | // Mapping for the inconsistent anonymous-union initializers check. | |||
5103 | RedundantUnionMap MemberUnions; | |||
5104 | ||||
5105 | bool HadError = false; | |||
5106 | for (unsigned i = 0; i < MemInits.size(); i++) { | |||
5107 | CXXCtorInitializer *Init = MemInits[i]; | |||
5108 | ||||
5109 | // Set the source order index. | |||
5110 | Init->setSourceOrder(i); | |||
5111 | ||||
5112 | if (Init->isAnyMemberInitializer()) { | |||
5113 | const void *Key = GetKeyForMember(Context, Init); | |||
5114 | if (CheckRedundantInit(*this, Init, Members[Key]) || | |||
5115 | CheckRedundantUnionInit(*this, Init, MemberUnions)) | |||
5116 | HadError = true; | |||
5117 | } else if (Init->isBaseInitializer()) { | |||
5118 | const void *Key = GetKeyForMember(Context, Init); | |||
5119 | if (CheckRedundantInit(*this, Init, Members[Key])) | |||
5120 | HadError = true; | |||
5121 | } else { | |||
5122 | assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void> (0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5122, __PRETTY_FUNCTION__)); | |||
5123 | // This must be the only initializer | |||
5124 | if (MemInits.size() != 1) { | |||
5125 | Diag(Init->getSourceLocation(), | |||
5126 | diag::err_delegating_initializer_alone) | |||
5127 | << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); | |||
5128 | // We will treat this as being the only initializer. | |||
5129 | } | |||
5130 | SetDelegatingInitializer(Constructor, MemInits[i]); | |||
5131 | // Return immediately as the initializer is set. | |||
5132 | return; | |||
5133 | } | |||
5134 | } | |||
5135 | ||||
5136 | if (HadError) | |||
5137 | return; | |||
5138 | ||||
5139 | DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); | |||
5140 | ||||
5141 | SetCtorInitializers(Constructor, AnyErrors, MemInits); | |||
5142 | ||||
5143 | DiagnoseUninitializedFields(*this, Constructor); | |||
5144 | } | |||
5145 | ||||
5146 | void | |||
5147 | Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, | |||
5148 | CXXRecordDecl *ClassDecl) { | |||
5149 | // Ignore dependent contexts. Also ignore unions, since their members never | |||
5150 | // have destructors implicitly called. | |||
5151 | if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) | |||
5152 | return; | |||
5153 | ||||
5154 | // FIXME: all the access-control diagnostics are positioned on the | |||
5155 | // field/base declaration. That's probably good; that said, the | |||
5156 | // user might reasonably want to know why the destructor is being | |||
5157 | // emitted, and we currently don't say. | |||
5158 | ||||
5159 | // Non-static data members. | |||
5160 | for (auto *Field : ClassDecl->fields()) { | |||
5161 | if (Field->isInvalidDecl()) | |||
5162 | continue; | |||
5163 | ||||
5164 | // Don't destroy incomplete or zero-length arrays. | |||
5165 | if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) | |||
5166 | continue; | |||
5167 | ||||
5168 | QualType FieldType = Context.getBaseElementType(Field->getType()); | |||
5169 | ||||
5170 | const RecordType* RT = FieldType->getAs<RecordType>(); | |||
5171 | if (!RT) | |||
5172 | continue; | |||
5173 | ||||
5174 | CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5175 | if (FieldClassDecl->isInvalidDecl()) | |||
5176 | continue; | |||
5177 | if (FieldClassDecl->hasIrrelevantDestructor()) | |||
5178 | continue; | |||
5179 | // The destructor for an implicit anonymous union member is never invoked. | |||
5180 | if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) | |||
5181 | continue; | |||
5182 | ||||
5183 | CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); | |||
5184 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5184, __PRETTY_FUNCTION__)); | |||
5185 | CheckDestructorAccess(Field->getLocation(), Dtor, | |||
5186 | PDiag(diag::err_access_dtor_field) | |||
5187 | << Field->getDeclName() | |||
5188 | << FieldType); | |||
5189 | ||||
5190 | MarkFunctionReferenced(Location, Dtor); | |||
5191 | DiagnoseUseOfDecl(Dtor, Location); | |||
5192 | } | |||
5193 | ||||
5194 | // We only potentially invoke the destructors of potentially constructed | |||
5195 | // subobjects. | |||
5196 | bool VisitVirtualBases = !ClassDecl->isAbstract(); | |||
5197 | ||||
5198 | llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; | |||
5199 | ||||
5200 | // Bases. | |||
5201 | for (const auto &Base : ClassDecl->bases()) { | |||
5202 | // Bases are always records in a well-formed non-dependent class. | |||
5203 | const RecordType *RT = Base.getType()->getAs<RecordType>(); | |||
5204 | ||||
5205 | // Remember direct virtual bases. | |||
5206 | if (Base.isVirtual()) { | |||
5207 | if (!VisitVirtualBases) | |||
5208 | continue; | |||
5209 | DirectVirtualBases.insert(RT); | |||
5210 | } | |||
5211 | ||||
5212 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5213 | // If our base class is invalid, we probably can't get its dtor anyway. | |||
5214 | if (BaseClassDecl->isInvalidDecl()) | |||
5215 | continue; | |||
5216 | if (BaseClassDecl->hasIrrelevantDestructor()) | |||
5217 | continue; | |||
5218 | ||||
5219 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | |||
5220 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5220, __PRETTY_FUNCTION__)); | |||
5221 | ||||
5222 | // FIXME: caret should be on the start of the class name | |||
5223 | CheckDestructorAccess(Base.getBeginLoc(), Dtor, | |||
5224 | PDiag(diag::err_access_dtor_base) | |||
5225 | << Base.getType() << Base.getSourceRange(), | |||
5226 | Context.getTypeDeclType(ClassDecl)); | |||
5227 | ||||
5228 | MarkFunctionReferenced(Location, Dtor); | |||
5229 | DiagnoseUseOfDecl(Dtor, Location); | |||
5230 | } | |||
5231 | ||||
5232 | if (!VisitVirtualBases) | |||
5233 | return; | |||
5234 | ||||
5235 | // Virtual bases. | |||
5236 | for (const auto &VBase : ClassDecl->vbases()) { | |||
5237 | // Bases are always records in a well-formed non-dependent class. | |||
5238 | const RecordType *RT = VBase.getType()->castAs<RecordType>(); | |||
5239 | ||||
5240 | // Ignore direct virtual bases. | |||
5241 | if (DirectVirtualBases.count(RT)) | |||
5242 | continue; | |||
5243 | ||||
5244 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5245 | // If our base class is invalid, we probably can't get its dtor anyway. | |||
5246 | if (BaseClassDecl->isInvalidDecl()) | |||
5247 | continue; | |||
5248 | if (BaseClassDecl->hasIrrelevantDestructor()) | |||
5249 | continue; | |||
5250 | ||||
5251 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | |||
5252 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5252, __PRETTY_FUNCTION__)); | |||
5253 | if (CheckDestructorAccess( | |||
5254 | ClassDecl->getLocation(), Dtor, | |||
5255 | PDiag(diag::err_access_dtor_vbase) | |||
5256 | << Context.getTypeDeclType(ClassDecl) << VBase.getType(), | |||
5257 | Context.getTypeDeclType(ClassDecl)) == | |||
5258 | AR_accessible) { | |||
5259 | CheckDerivedToBaseConversion( | |||
5260 | Context.getTypeDeclType(ClassDecl), VBase.getType(), | |||
5261 | diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), | |||
5262 | SourceRange(), DeclarationName(), nullptr); | |||
5263 | } | |||
5264 | ||||
5265 | MarkFunctionReferenced(Location, Dtor); | |||
5266 | DiagnoseUseOfDecl(Dtor, Location); | |||
5267 | } | |||
5268 | } | |||
5269 | ||||
5270 | void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { | |||
5271 | if (!CDtorDecl) | |||
5272 | return; | |||
5273 | ||||
5274 | if (CXXConstructorDecl *Constructor | |||
5275 | = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { | |||
5276 | SetCtorInitializers(Constructor, /*AnyErrors=*/false); | |||
5277 | DiagnoseUninitializedFields(*this, Constructor); | |||
5278 | } | |||
5279 | } | |||
5280 | ||||
5281 | bool Sema::isAbstractType(SourceLocation Loc, QualType T) { | |||
5282 | if (!getLangOpts().CPlusPlus) | |||
5283 | return false; | |||
5284 | ||||
5285 | const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); | |||
5286 | if (!RD) | |||
5287 | return false; | |||
5288 | ||||
5289 | // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a | |||
5290 | // class template specialization here, but doing so breaks a lot of code. | |||
5291 | ||||
5292 | // We can't answer whether something is abstract until it has a | |||
5293 | // definition. If it's currently being defined, we'll walk back | |||
5294 | // over all the declarations when we have a full definition. | |||
5295 | const CXXRecordDecl *Def = RD->getDefinition(); | |||
5296 | if (!Def || Def->isBeingDefined()) | |||
5297 | return false; | |||
5298 | ||||
5299 | return RD->isAbstract(); | |||
5300 | } | |||
5301 | ||||
5302 | bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, | |||
5303 | TypeDiagnoser &Diagnoser) { | |||
5304 | if (!isAbstractType(Loc, T)) | |||
5305 | return false; | |||
5306 | ||||
5307 | T = Context.getBaseElementType(T); | |||
5308 | Diagnoser.diagnose(*this, Loc, T); | |||
5309 | DiagnoseAbstractType(T->getAsCXXRecordDecl()); | |||
5310 | return true; | |||
5311 | } | |||
5312 | ||||
5313 | void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { | |||
5314 | // Check if we've already emitted the list of pure virtual functions | |||
5315 | // for this class. | |||
5316 | if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) | |||
5317 | return; | |||
5318 | ||||
5319 | // If the diagnostic is suppressed, don't emit the notes. We're only | |||
5320 | // going to emit them once, so try to attach them to a diagnostic we're | |||
5321 | // actually going to show. | |||
5322 | if (Diags.isLastDiagnosticIgnored()) | |||
5323 | return; | |||
5324 | ||||
5325 | CXXFinalOverriderMap FinalOverriders; | |||
5326 | RD->getFinalOverriders(FinalOverriders); | |||
5327 | ||||
5328 | // Keep a set of seen pure methods so we won't diagnose the same method | |||
5329 | // more than once. | |||
5330 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; | |||
5331 | ||||
5332 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | |||
5333 | MEnd = FinalOverriders.end(); | |||
5334 | M != MEnd; | |||
5335 | ++M) { | |||
5336 | for (OverridingMethods::iterator SO = M->second.begin(), | |||
5337 | SOEnd = M->second.end(); | |||
5338 | SO != SOEnd; ++SO) { | |||
5339 | // C++ [class.abstract]p4: | |||
5340 | // A class is abstract if it contains or inherits at least one | |||
5341 | // pure virtual function for which the final overrider is pure | |||
5342 | // virtual. | |||
5343 | ||||
5344 | // | |||
5345 | if (SO->second.size() != 1) | |||
5346 | continue; | |||
5347 | ||||
5348 | if (!SO->second.front().Method->isPure()) | |||
5349 | continue; | |||
5350 | ||||
5351 | if (!SeenPureMethods.insert(SO->second.front().Method).second) | |||
5352 | continue; | |||
5353 | ||||
5354 | Diag(SO->second.front().Method->getLocation(), | |||
5355 | diag::note_pure_virtual_function) | |||
5356 | << SO->second.front().Method->getDeclName() << RD->getDeclName(); | |||
5357 | } | |||
5358 | } | |||
5359 | ||||
5360 | if (!PureVirtualClassDiagSet) | |||
5361 | PureVirtualClassDiagSet.reset(new RecordDeclSetTy); | |||
5362 | PureVirtualClassDiagSet->insert(RD); | |||
5363 | } | |||
5364 | ||||
5365 | namespace { | |||
5366 | struct AbstractUsageInfo { | |||
5367 | Sema &S; | |||
5368 | CXXRecordDecl *Record; | |||
5369 | CanQualType AbstractType; | |||
5370 | bool Invalid; | |||
5371 | ||||
5372 | AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) | |||
5373 | : S(S), Record(Record), | |||
5374 | AbstractType(S.Context.getCanonicalType( | |||
5375 | S.Context.getTypeDeclType(Record))), | |||
5376 | Invalid(false) {} | |||
5377 | ||||
5378 | void DiagnoseAbstractType() { | |||
5379 | if (Invalid) return; | |||
5380 | S.DiagnoseAbstractType(Record); | |||
5381 | Invalid = true; | |||
5382 | } | |||
5383 | ||||
5384 | void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); | |||
5385 | }; | |||
5386 | ||||
5387 | struct CheckAbstractUsage { | |||
5388 | AbstractUsageInfo &Info; | |||
5389 | const NamedDecl *Ctx; | |||
5390 | ||||
5391 | CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) | |||
5392 | : Info(Info), Ctx(Ctx) {} | |||
5393 | ||||
5394 | void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5395 | switch (TL.getTypeLocClass()) { | |||
5396 | #define ABSTRACT_TYPELOC(CLASS, PARENT) | |||
5397 | #define TYPELOC(CLASS, PARENT) \ | |||
5398 | case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; | |||
5399 | #include "clang/AST/TypeLocNodes.def" | |||
5400 | } | |||
5401 | } | |||
5402 | ||||
5403 | void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5404 | Visit(TL.getReturnLoc(), Sema::AbstractReturnType); | |||
5405 | for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { | |||
5406 | if (!TL.getParam(I)) | |||
5407 | continue; | |||
5408 | ||||
5409 | TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); | |||
5410 | if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); | |||
5411 | } | |||
5412 | } | |||
5413 | ||||
5414 | void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5415 | Visit(TL.getElementLoc(), Sema::AbstractArrayType); | |||
5416 | } | |||
5417 | ||||
5418 | void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5419 | // Visit the type parameters from a permissive context. | |||
5420 | for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { | |||
5421 | TemplateArgumentLoc TAL = TL.getArgLoc(I); | |||
5422 | if (TAL.getArgument().getKind() == TemplateArgument::Type) | |||
5423 | if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) | |||
5424 | Visit(TSI->getTypeLoc(), Sema::AbstractNone); | |||
5425 | // TODO: other template argument types? | |||
5426 | } | |||
5427 | } | |||
5428 | ||||
5429 | // Visit pointee types from a permissive context. | |||
5430 | #define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc (), Sema::AbstractNone); } \ | |||
5431 | void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ | |||
5432 | Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ | |||
5433 | } | |||
5434 | CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5435 | CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5436 | CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5437 | CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5438 | CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5439 | ||||
5440 | /// Handle all the types we haven't given a more specific | |||
5441 | /// implementation for above. | |||
5442 | void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5443 | // Every other kind of type that we haven't called out already | |||
5444 | // that has an inner type is either (1) sugar or (2) contains that | |||
5445 | // inner type in some way as a subobject. | |||
5446 | if (TypeLoc Next = TL.getNextTypeLoc()) | |||
5447 | return Visit(Next, Sel); | |||
5448 | ||||
5449 | // If there's no inner type and we're in a permissive context, | |||
5450 | // don't diagnose. | |||
5451 | if (Sel == Sema::AbstractNone) return; | |||
5452 | ||||
5453 | // Check whether the type matches the abstract type. | |||
5454 | QualType T = TL.getType(); | |||
5455 | if (T->isArrayType()) { | |||
5456 | Sel = Sema::AbstractArrayType; | |||
5457 | T = Info.S.Context.getBaseElementType(T); | |||
5458 | } | |||
5459 | CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); | |||
5460 | if (CT != Info.AbstractType) return; | |||
5461 | ||||
5462 | // It matched; do some magic. | |||
5463 | if (Sel == Sema::AbstractArrayType) { | |||
5464 | Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) | |||
5465 | << T << TL.getSourceRange(); | |||
5466 | } else { | |||
5467 | Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) | |||
5468 | << Sel << T << TL.getSourceRange(); | |||
5469 | } | |||
5470 | Info.DiagnoseAbstractType(); | |||
5471 | } | |||
5472 | }; | |||
5473 | ||||
5474 | void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, | |||
5475 | Sema::AbstractDiagSelID Sel) { | |||
5476 | CheckAbstractUsage(*this, D).Visit(TL, Sel); | |||
5477 | } | |||
5478 | ||||
5479 | } | |||
5480 | ||||
5481 | /// Check for invalid uses of an abstract type in a method declaration. | |||
5482 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | |||
5483 | CXXMethodDecl *MD) { | |||
5484 | // No need to do the check on definitions, which require that | |||
5485 | // the return/param types be complete. | |||
5486 | if (MD->doesThisDeclarationHaveABody()) | |||
5487 | return; | |||
5488 | ||||
5489 | // For safety's sake, just ignore it if we don't have type source | |||
5490 | // information. This should never happen for non-implicit methods, | |||
5491 | // but... | |||
5492 | if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) | |||
5493 | Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); | |||
5494 | } | |||
5495 | ||||
5496 | /// Check for invalid uses of an abstract type within a class definition. | |||
5497 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | |||
5498 | CXXRecordDecl *RD) { | |||
5499 | for (auto *D : RD->decls()) { | |||
5500 | if (D->isImplicit()) continue; | |||
5501 | ||||
5502 | // Methods and method templates. | |||
5503 | if (isa<CXXMethodDecl>(D)) { | |||
5504 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); | |||
5505 | } else if (isa<FunctionTemplateDecl>(D)) { | |||
5506 | FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); | |||
5507 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); | |||
5508 | ||||
5509 | // Fields and static variables. | |||
5510 | } else if (isa<FieldDecl>(D)) { | |||
5511 | FieldDecl *FD = cast<FieldDecl>(D); | |||
5512 | if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) | |||
5513 | Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); | |||
5514 | } else if (isa<VarDecl>(D)) { | |||
5515 | VarDecl *VD = cast<VarDecl>(D); | |||
5516 | if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) | |||
5517 | Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); | |||
5518 | ||||
5519 | // Nested classes and class templates. | |||
5520 | } else if (isa<CXXRecordDecl>(D)) { | |||
5521 | CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); | |||
5522 | } else if (isa<ClassTemplateDecl>(D)) { | |||
5523 | CheckAbstractClassUsage(Info, | |||
5524 | cast<ClassTemplateDecl>(D)->getTemplatedDecl()); | |||
5525 | } | |||
5526 | } | |||
5527 | } | |||
5528 | ||||
5529 | static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { | |||
5530 | Attr *ClassAttr = getDLLAttr(Class); | |||
5531 | if (!ClassAttr) | |||
5532 | return; | |||
5533 | ||||
5534 | assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast< void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5534, __PRETTY_FUNCTION__)); | |||
5535 | ||||
5536 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | |||
5537 | ||||
5538 | if (TSK == TSK_ExplicitInstantiationDeclaration) | |||
5539 | // Don't go any further if this is just an explicit instantiation | |||
5540 | // declaration. | |||
5541 | return; | |||
5542 | ||||
5543 | if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) | |||
5544 | S.MarkVTableUsed(Class->getLocation(), Class, true); | |||
5545 | ||||
5546 | for (Decl *Member : Class->decls()) { | |||
5547 | // Defined static variables that are members of an exported base | |||
5548 | // class must be marked export too. | |||
5549 | auto *VD = dyn_cast<VarDecl>(Member); | |||
5550 | if (VD && Member->getAttr<DLLExportAttr>() && | |||
5551 | VD->getStorageClass() == SC_Static && | |||
5552 | TSK == TSK_ImplicitInstantiation) | |||
5553 | S.MarkVariableReferenced(VD->getLocation(), VD); | |||
5554 | ||||
5555 | auto *MD = dyn_cast<CXXMethodDecl>(Member); | |||
5556 | if (!MD) | |||
5557 | continue; | |||
5558 | ||||
5559 | if (Member->getAttr<DLLExportAttr>()) { | |||
5560 | if (MD->isUserProvided()) { | |||
5561 | // Instantiate non-default class member functions ... | |||
5562 | ||||
5563 | // .. except for certain kinds of template specializations. | |||
5564 | if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) | |||
5565 | continue; | |||
5566 | ||||
5567 | S.MarkFunctionReferenced(Class->getLocation(), MD); | |||
5568 | ||||
5569 | // The function will be passed to the consumer when its definition is | |||
5570 | // encountered. | |||
5571 | } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || | |||
5572 | MD->isCopyAssignmentOperator() || | |||
5573 | MD->isMoveAssignmentOperator()) { | |||
5574 | // Synthesize and instantiate non-trivial implicit methods, explicitly | |||
5575 | // defaulted methods, and the copy and move assignment operators. The | |||
5576 | // latter are exported even if they are trivial, because the address of | |||
5577 | // an operator can be taken and should compare equal across libraries. | |||
5578 | DiagnosticErrorTrap Trap(S.Diags); | |||
5579 | S.MarkFunctionReferenced(Class->getLocation(), MD); | |||
5580 | if (Trap.hasErrorOccurred()) { | |||
5581 | S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) | |||
5582 | << Class << !S.getLangOpts().CPlusPlus11; | |||
5583 | break; | |||
5584 | } | |||
5585 | ||||
5586 | // There is no later point when we will see the definition of this | |||
5587 | // function, so pass it to the consumer now. | |||
5588 | S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); | |||
5589 | } | |||
5590 | } | |||
5591 | } | |||
5592 | } | |||
5593 | ||||
5594 | static void checkForMultipleExportedDefaultConstructors(Sema &S, | |||
5595 | CXXRecordDecl *Class) { | |||
5596 | // Only the MS ABI has default constructor closures, so we don't need to do | |||
5597 | // this semantic checking anywhere else. | |||
5598 | if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
5599 | return; | |||
5600 | ||||
5601 | CXXConstructorDecl *LastExportedDefaultCtor = nullptr; | |||
5602 | for (Decl *Member : Class->decls()) { | |||
5603 | // Look for exported default constructors. | |||
5604 | auto *CD = dyn_cast<CXXConstructorDecl>(Member); | |||
5605 | if (!CD || !CD->isDefaultConstructor()) | |||
5606 | continue; | |||
5607 | auto *Attr = CD->getAttr<DLLExportAttr>(); | |||
5608 | if (!Attr) | |||
5609 | continue; | |||
5610 | ||||
5611 | // If the class is non-dependent, mark the default arguments as ODR-used so | |||
5612 | // that we can properly codegen the constructor closure. | |||
5613 | if (!Class->isDependentContext()) { | |||
5614 | for (ParmVarDecl *PD : CD->parameters()) { | |||
5615 | (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); | |||
5616 | S.DiscardCleanupsInEvaluationContext(); | |||
5617 | } | |||
5618 | } | |||
5619 | ||||
5620 | if (LastExportedDefaultCtor) { | |||
5621 | S.Diag(LastExportedDefaultCtor->getLocation(), | |||
5622 | diag::err_attribute_dll_ambiguous_default_ctor) | |||
5623 | << Class; | |||
5624 | S.Diag(CD->getLocation(), diag::note_entity_declared_at) | |||
5625 | << CD->getDeclName(); | |||
5626 | return; | |||
5627 | } | |||
5628 | LastExportedDefaultCtor = CD; | |||
5629 | } | |||
5630 | } | |||
5631 | ||||
5632 | void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { | |||
5633 | // Mark any compiler-generated routines with the implicit code_seg attribute. | |||
5634 | for (auto *Method : Class->methods()) { | |||
5635 | if (Method->isUserProvided()) | |||
5636 | continue; | |||
5637 | if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) | |||
5638 | Method->addAttr(A); | |||
5639 | } | |||
5640 | } | |||
5641 | ||||
5642 | /// Check class-level dllimport/dllexport attribute. | |||
5643 | void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { | |||
5644 | Attr *ClassAttr = getDLLAttr(Class); | |||
5645 | ||||
5646 | // MSVC inherits DLL attributes to partial class template specializations. | |||
5647 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { | |||
5648 | if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { | |||
5649 | if (Attr *TemplateAttr = | |||
5650 | getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { | |||
5651 | auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); | |||
5652 | A->setInherited(true); | |||
5653 | ClassAttr = A; | |||
5654 | } | |||
5655 | } | |||
5656 | } | |||
5657 | ||||
5658 | if (!ClassAttr) | |||
5659 | return; | |||
5660 | ||||
5661 | if (!Class->isExternallyVisible()) { | |||
5662 | Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) | |||
5663 | << Class << ClassAttr; | |||
5664 | return; | |||
5665 | } | |||
5666 | ||||
5667 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
5668 | !ClassAttr->isInherited()) { | |||
5669 | // Diagnose dll attributes on members of class with dll attribute. | |||
5670 | for (Decl *Member : Class->decls()) { | |||
5671 | if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) | |||
5672 | continue; | |||
5673 | InheritableAttr *MemberAttr = getDLLAttr(Member); | |||
5674 | if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) | |||
5675 | continue; | |||
5676 | ||||
5677 | Diag(MemberAttr->getLocation(), | |||
5678 | diag::err_attribute_dll_member_of_dll_class) | |||
5679 | << MemberAttr << ClassAttr; | |||
5680 | Diag(ClassAttr->getLocation(), diag::note_previous_attribute); | |||
5681 | Member->setInvalidDecl(); | |||
5682 | } | |||
5683 | } | |||
5684 | ||||
5685 | if (Class->getDescribedClassTemplate()) | |||
5686 | // Don't inherit dll attribute until the template is instantiated. | |||
5687 | return; | |||
5688 | ||||
5689 | // The class is either imported or exported. | |||
5690 | const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; | |||
5691 | ||||
5692 | // Check if this was a dllimport attribute propagated from a derived class to | |||
5693 | // a base class template specialization. We don't apply these attributes to | |||
5694 | // static data members. | |||
5695 | const bool PropagatedImport = | |||
5696 | !ClassExported && | |||
5697 | cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); | |||
5698 | ||||
5699 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | |||
5700 | ||||
5701 | // Ignore explicit dllexport on explicit class template instantiation | |||
5702 | // declarations, except in MinGW mode. | |||
5703 | if (ClassExported && !ClassAttr->isInherited() && | |||
5704 | TSK == TSK_ExplicitInstantiationDeclaration && | |||
5705 | !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { | |||
5706 | Class->dropAttr<DLLExportAttr>(); | |||
5707 | return; | |||
5708 | } | |||
5709 | ||||
5710 | // Force declaration of implicit members so they can inherit the attribute. | |||
5711 | ForceDeclarationOfImplicitMembers(Class); | |||
5712 | ||||
5713 | // FIXME: MSVC's docs say all bases must be exportable, but this doesn't | |||
5714 | // seem to be true in practice? | |||
5715 | ||||
5716 | for (Decl *Member : Class->decls()) { | |||
5717 | VarDecl *VD = dyn_cast<VarDecl>(Member); | |||
5718 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); | |||
5719 | ||||
5720 | // Only methods and static fields inherit the attributes. | |||
5721 | if (!VD && !MD) | |||
5722 | continue; | |||
5723 | ||||
5724 | if (MD) { | |||
5725 | // Don't process deleted methods. | |||
5726 | if (MD->isDeleted()) | |||
5727 | continue; | |||
5728 | ||||
5729 | if (MD->isInlined()) { | |||
5730 | // MinGW does not import or export inline methods. But do it for | |||
5731 | // template instantiations. | |||
5732 | if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
5733 | !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && | |||
5734 | TSK != TSK_ExplicitInstantiationDeclaration && | |||
5735 | TSK != TSK_ExplicitInstantiationDefinition) | |||
5736 | continue; | |||
5737 | ||||
5738 | // MSVC versions before 2015 don't export the move assignment operators | |||
5739 | // and move constructor, so don't attempt to import/export them if | |||
5740 | // we have a definition. | |||
5741 | auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); | |||
5742 | if ((MD->isMoveAssignmentOperator() || | |||
5743 | (Ctor && Ctor->isMoveConstructor())) && | |||
5744 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) | |||
5745 | continue; | |||
5746 | ||||
5747 | // MSVC2015 doesn't export trivial defaulted x-tor but copy assign | |||
5748 | // operator is exported anyway. | |||
5749 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
5750 | (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) | |||
5751 | continue; | |||
5752 | } | |||
5753 | } | |||
5754 | ||||
5755 | // Don't apply dllimport attributes to static data members of class template | |||
5756 | // instantiations when the attribute is propagated from a derived class. | |||
5757 | if (VD && PropagatedImport) | |||
5758 | continue; | |||
5759 | ||||
5760 | if (!cast<NamedDecl>(Member)->isExternallyVisible()) | |||
5761 | continue; | |||
5762 | ||||
5763 | if (!getDLLAttr(Member)) { | |||
5764 | InheritableAttr *NewAttr = nullptr; | |||
5765 | ||||
5766 | // Do not export/import inline function when -fno-dllexport-inlines is | |||
5767 | // passed. But add attribute for later local static var check. | |||
5768 | if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && | |||
5769 | TSK != TSK_ExplicitInstantiationDeclaration && | |||
5770 | TSK != TSK_ExplicitInstantiationDefinition) { | |||
5771 | if (ClassExported) { | |||
5772 | NewAttr = ::new (getASTContext()) | |||
5773 | DLLExportStaticLocalAttr(ClassAttr->getRange(), | |||
5774 | getASTContext(), | |||
5775 | ClassAttr->getSpellingListIndex()); | |||
5776 | } else { | |||
5777 | NewAttr = ::new (getASTContext()) | |||
5778 | DLLImportStaticLocalAttr(ClassAttr->getRange(), | |||
5779 | getASTContext(), | |||
5780 | ClassAttr->getSpellingListIndex()); | |||
5781 | } | |||
5782 | } else { | |||
5783 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
5784 | } | |||
5785 | ||||
5786 | NewAttr->setInherited(true); | |||
5787 | Member->addAttr(NewAttr); | |||
5788 | ||||
5789 | if (MD) { | |||
5790 | // Propagate DLLAttr to friend re-declarations of MD that have already | |||
5791 | // been constructed. | |||
5792 | for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; | |||
5793 | FD = FD->getPreviousDecl()) { | |||
5794 | if (FD->getFriendObjectKind() == Decl::FOK_None) | |||
5795 | continue; | |||
5796 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5797, __PRETTY_FUNCTION__)) | |||
5797 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5797, __PRETTY_FUNCTION__)); | |||
5798 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
5799 | NewAttr->setInherited(true); | |||
5800 | FD->addAttr(NewAttr); | |||
5801 | } | |||
5802 | } | |||
5803 | } | |||
5804 | } | |||
5805 | ||||
5806 | if (ClassExported) | |||
5807 | DelayedDllExportClasses.push_back(Class); | |||
5808 | } | |||
5809 | ||||
5810 | /// Perform propagation of DLL attributes from a derived class to a | |||
5811 | /// templated base class for MS compatibility. | |||
5812 | void Sema::propagateDLLAttrToBaseClassTemplate( | |||
5813 | CXXRecordDecl *Class, Attr *ClassAttr, | |||
5814 | ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { | |||
5815 | if (getDLLAttr( | |||
5816 | BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { | |||
5817 | // If the base class template has a DLL attribute, don't try to change it. | |||
5818 | return; | |||
5819 | } | |||
5820 | ||||
5821 | auto TSK = BaseTemplateSpec->getSpecializationKind(); | |||
5822 | if (!getDLLAttr(BaseTemplateSpec) && | |||
5823 | (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || | |||
5824 | TSK == TSK_ImplicitInstantiation)) { | |||
5825 | // The template hasn't been instantiated yet (or it has, but only as an | |||
5826 | // explicit instantiation declaration or implicit instantiation, which means | |||
5827 | // we haven't codegenned any members yet), so propagate the attribute. | |||
5828 | auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
5829 | NewAttr->setInherited(true); | |||
5830 | BaseTemplateSpec->addAttr(NewAttr); | |||
5831 | ||||
5832 | // If this was an import, mark that we propagated it from a derived class to | |||
5833 | // a base class template specialization. | |||
5834 | if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) | |||
5835 | ImportAttr->setPropagatedToBaseTemplate(); | |||
5836 | ||||
5837 | // If the template is already instantiated, checkDLLAttributeRedeclaration() | |||
5838 | // needs to be run again to work see the new attribute. Otherwise this will | |||
5839 | // get run whenever the template is instantiated. | |||
5840 | if (TSK != TSK_Undeclared) | |||
5841 | checkClassLevelDLLAttribute(BaseTemplateSpec); | |||
5842 | ||||
5843 | return; | |||
5844 | } | |||
5845 | ||||
5846 | if (getDLLAttr(BaseTemplateSpec)) { | |||
5847 | // The template has already been specialized or instantiated with an | |||
5848 | // attribute, explicitly or through propagation. We should not try to change | |||
5849 | // it. | |||
5850 | return; | |||
5851 | } | |||
5852 | ||||
5853 | // The template was previously instantiated or explicitly specialized without | |||
5854 | // a dll attribute, It's too late for us to add an attribute, so warn that | |||
5855 | // this is unsupported. | |||
5856 | Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) | |||
5857 | << BaseTemplateSpec->isExplicitSpecialization(); | |||
5858 | Diag(ClassAttr->getLocation(), diag::note_attribute); | |||
5859 | if (BaseTemplateSpec->isExplicitSpecialization()) { | |||
5860 | Diag(BaseTemplateSpec->getLocation(), | |||
5861 | diag::note_template_class_explicit_specialization_was_here) | |||
5862 | << BaseTemplateSpec; | |||
5863 | } else { | |||
5864 | Diag(BaseTemplateSpec->getPointOfInstantiation(), | |||
5865 | diag::note_template_class_instantiation_was_here) | |||
5866 | << BaseTemplateSpec; | |||
5867 | } | |||
5868 | } | |||
5869 | ||||
5870 | static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, | |||
5871 | SourceLocation DefaultLoc) { | |||
5872 | switch (S.getSpecialMember(MD)) { | |||
5873 | case Sema::CXXDefaultConstructor: | |||
5874 | S.DefineImplicitDefaultConstructor(DefaultLoc, | |||
5875 | cast<CXXConstructorDecl>(MD)); | |||
5876 | break; | |||
5877 | case Sema::CXXCopyConstructor: | |||
5878 | S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | |||
5879 | break; | |||
5880 | case Sema::CXXCopyAssignment: | |||
5881 | S.DefineImplicitCopyAssignment(DefaultLoc, MD); | |||
5882 | break; | |||
5883 | case Sema::CXXDestructor: | |||
5884 | S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); | |||
5885 | break; | |||
5886 | case Sema::CXXMoveConstructor: | |||
5887 | S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | |||
5888 | break; | |||
5889 | case Sema::CXXMoveAssignment: | |||
5890 | S.DefineImplicitMoveAssignment(DefaultLoc, MD); | |||
5891 | break; | |||
5892 | case Sema::CXXInvalid: | |||
5893 | llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5893); | |||
5894 | } | |||
5895 | } | |||
5896 | ||||
5897 | /// Determine whether a type is permitted to be passed or returned in | |||
5898 | /// registers, per C++ [class.temporary]p3. | |||
5899 | static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, | |||
5900 | TargetInfo::CallingConvKind CCK) { | |||
5901 | if (D->isDependentType() || D->isInvalidDecl()) | |||
5902 | return false; | |||
5903 | ||||
5904 | // Clang <= 4 used the pre-C++11 rule, which ignores move operations. | |||
5905 | // The PS4 platform ABI follows the behavior of Clang 3.2. | |||
5906 | if (CCK == TargetInfo::CCK_ClangABI4OrPS4) | |||
5907 | return !D->hasNonTrivialDestructorForCall() && | |||
5908 | !D->hasNonTrivialCopyConstructorForCall(); | |||
5909 | ||||
5910 | if (CCK == TargetInfo::CCK_MicrosoftWin64) { | |||
5911 | bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; | |||
5912 | bool DtorIsTrivialForCall = false; | |||
5913 | ||||
5914 | // If a class has at least one non-deleted, trivial copy constructor, it | |||
5915 | // is passed according to the C ABI. Otherwise, it is passed indirectly. | |||
5916 | // | |||
5917 | // Note: This permits classes with non-trivial copy or move ctors to be | |||
5918 | // passed in registers, so long as they *also* have a trivial copy ctor, | |||
5919 | // which is non-conforming. | |||
5920 | if (D->needsImplicitCopyConstructor()) { | |||
5921 | if (!D->defaultedCopyConstructorIsDeleted()) { | |||
5922 | if (D->hasTrivialCopyConstructor()) | |||
5923 | CopyCtorIsTrivial = true; | |||
5924 | if (D->hasTrivialCopyConstructorForCall()) | |||
5925 | CopyCtorIsTrivialForCall = true; | |||
5926 | } | |||
5927 | } else { | |||
5928 | for (const CXXConstructorDecl *CD : D->ctors()) { | |||
5929 | if (CD->isCopyConstructor() && !CD->isDeleted()) { | |||
5930 | if (CD->isTrivial()) | |||
5931 | CopyCtorIsTrivial = true; | |||
5932 | if (CD->isTrivialForCall()) | |||
5933 | CopyCtorIsTrivialForCall = true; | |||
5934 | } | |||
5935 | } | |||
5936 | } | |||
5937 | ||||
5938 | if (D->needsImplicitDestructor()) { | |||
5939 | if (!D->defaultedDestructorIsDeleted() && | |||
5940 | D->hasTrivialDestructorForCall()) | |||
5941 | DtorIsTrivialForCall = true; | |||
5942 | } else if (const auto *DD = D->getDestructor()) { | |||
5943 | if (!DD->isDeleted() && DD->isTrivialForCall()) | |||
5944 | DtorIsTrivialForCall = true; | |||
5945 | } | |||
5946 | ||||
5947 | // If the copy ctor and dtor are both trivial-for-calls, pass direct. | |||
5948 | if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) | |||
5949 | return true; | |||
5950 | ||||
5951 | // If a class has a destructor, we'd really like to pass it indirectly | |||
5952 | // because it allows us to elide copies. Unfortunately, MSVC makes that | |||
5953 | // impossible for small types, which it will pass in a single register or | |||
5954 | // stack slot. Most objects with dtors are large-ish, so handle that early. | |||
5955 | // We can't call out all large objects as being indirect because there are | |||
5956 | // multiple x64 calling conventions and the C++ ABI code shouldn't dictate | |||
5957 | // how we pass large POD types. | |||
5958 | ||||
5959 | // Note: This permits small classes with nontrivial destructors to be | |||
5960 | // passed in registers, which is non-conforming. | |||
5961 | bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); | |||
5962 | uint64_t TypeSize = isAArch64 ? 128 : 64; | |||
5963 | ||||
5964 | if (CopyCtorIsTrivial && | |||
5965 | S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) | |||
5966 | return true; | |||
5967 | return false; | |||
5968 | } | |||
5969 | ||||
5970 | // Per C++ [class.temporary]p3, the relevant condition is: | |||
5971 | // each copy constructor, move constructor, and destructor of X is | |||
5972 | // either trivial or deleted, and X has at least one non-deleted copy | |||
5973 | // or move constructor | |||
5974 | bool HasNonDeletedCopyOrMove = false; | |||
5975 | ||||
5976 | if (D->needsImplicitCopyConstructor() && | |||
5977 | !D->defaultedCopyConstructorIsDeleted()) { | |||
5978 | if (!D->hasTrivialCopyConstructorForCall()) | |||
5979 | return false; | |||
5980 | HasNonDeletedCopyOrMove = true; | |||
5981 | } | |||
5982 | ||||
5983 | if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && | |||
5984 | !D->defaultedMoveConstructorIsDeleted()) { | |||
5985 | if (!D->hasTrivialMoveConstructorForCall()) | |||
5986 | return false; | |||
5987 | HasNonDeletedCopyOrMove = true; | |||
5988 | } | |||
5989 | ||||
5990 | if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && | |||
5991 | !D->hasTrivialDestructorForCall()) | |||
5992 | return false; | |||
5993 | ||||
5994 | for (const CXXMethodDecl *MD : D->methods()) { | |||
5995 | if (MD->isDeleted()) | |||
5996 | continue; | |||
5997 | ||||
5998 | auto *CD = dyn_cast<CXXConstructorDecl>(MD); | |||
5999 | if (CD && CD->isCopyOrMoveConstructor()) | |||
6000 | HasNonDeletedCopyOrMove = true; | |||
6001 | else if (!isa<CXXDestructorDecl>(MD)) | |||
6002 | continue; | |||
6003 | ||||
6004 | if (!MD->isTrivialForCall()) | |||
6005 | return false; | |||
6006 | } | |||
6007 | ||||
6008 | return HasNonDeletedCopyOrMove; | |||
6009 | } | |||
6010 | ||||
6011 | /// Perform semantic checks on a class definition that has been | |||
6012 | /// completing, introducing implicitly-declared members, checking for | |||
6013 | /// abstract types, etc. | |||
6014 | void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { | |||
6015 | if (!Record) | |||
6016 | return; | |||
6017 | ||||
6018 | if (Record->isAbstract() && !Record->isInvalidDecl()) { | |||
6019 | AbstractUsageInfo Info(*this, Record); | |||
6020 | CheckAbstractClassUsage(Info, Record); | |||
6021 | } | |||
6022 | ||||
6023 | // If this is not an aggregate type and has no user-declared constructor, | |||
6024 | // complain about any non-static data members of reference or const scalar | |||
6025 | // type, since they will never get initializers. | |||
6026 | if (!Record->isInvalidDecl() && !Record->isDependentType() && | |||
6027 | !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && | |||
6028 | !Record->isLambda()) { | |||
6029 | bool Complained = false; | |||
6030 | for (const auto *F : Record->fields()) { | |||
6031 | if (F->hasInClassInitializer() || F->isUnnamedBitfield()) | |||
6032 | continue; | |||
6033 | ||||
6034 | if (F->getType()->isReferenceType() || | |||
6035 | (F->getType().isConstQualified() && F->getType()->isScalarType())) { | |||
6036 | if (!Complained) { | |||
6037 | Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) | |||
6038 | << Record->getTagKind() << Record; | |||
6039 | Complained = true; | |||
6040 | } | |||
6041 | ||||
6042 | Diag(F->getLocation(), diag::note_refconst_member_not_initialized) | |||
6043 | << F->getType()->isReferenceType() | |||
6044 | << F->getDeclName(); | |||
6045 | } | |||
6046 | } | |||
6047 | } | |||
6048 | ||||
6049 | if (Record->getIdentifier()) { | |||
6050 | // C++ [class.mem]p13: | |||
6051 | // If T is the name of a class, then each of the following shall have a | |||
6052 | // name different from T: | |||
6053 | // - every member of every anonymous union that is a member of class T. | |||
6054 | // | |||
6055 | // C++ [class.mem]p14: | |||
6056 | // In addition, if class T has a user-declared constructor (12.1), every | |||
6057 | // non-static data member of class T shall have a name different from T. | |||
6058 | DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); | |||
6059 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; | |||
6060 | ++I) { | |||
6061 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
6062 | if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && | |||
6063 | Record->hasUserDeclaredConstructor()) || | |||
6064 | isa<IndirectFieldDecl>(D)) { | |||
6065 | Diag((*I)->getLocation(), diag::err_member_name_of_class) | |||
6066 | << D->getDeclName(); | |||
6067 | break; | |||
6068 | } | |||
6069 | } | |||
6070 | } | |||
6071 | ||||
6072 | // Warn if the class has virtual methods but non-virtual public destructor. | |||
6073 | if (Record->isPolymorphic() && !Record->isDependentType()) { | |||
6074 | CXXDestructorDecl *dtor = Record->getDestructor(); | |||
6075 | if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && | |||
6076 | !Record->hasAttr<FinalAttr>()) | |||
6077 | Diag(dtor ? dtor->getLocation() : Record->getLocation(), | |||
6078 | diag::warn_non_virtual_dtor) << Context.getRecordType(Record); | |||
6079 | } | |||
6080 | ||||
6081 | if (Record->isAbstract()) { | |||
6082 | if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { | |||
6083 | Diag(Record->getLocation(), diag::warn_abstract_final_class) | |||
6084 | << FA->isSpelledAsSealed(); | |||
6085 | DiagnoseAbstractType(Record); | |||
6086 | } | |||
6087 | } | |||
6088 | ||||
6089 | // See if trivial_abi has to be dropped. | |||
6090 | if (Record->hasAttr<TrivialABIAttr>()) | |||
6091 | checkIllFormedTrivialABIStruct(*Record); | |||
6092 | ||||
6093 | // Set HasTrivialSpecialMemberForCall if the record has attribute | |||
6094 | // "trivial_abi". | |||
6095 | bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); | |||
6096 | ||||
6097 | if (HasTrivialABI) | |||
6098 | Record->setHasTrivialSpecialMemberForCall(); | |||
6099 | ||||
6100 | bool HasMethodWithOverrideControl = false, | |||
6101 | HasOverridingMethodWithoutOverrideControl = false; | |||
6102 | if (!Record->isDependentType()) { | |||
6103 | for (auto *M : Record->methods()) { | |||
6104 | // See if a method overloads virtual methods in a base | |||
6105 | // class without overriding any. | |||
6106 | if (!M->isStatic()) | |||
6107 | DiagnoseHiddenVirtualMethods(M); | |||
6108 | if (M->hasAttr<OverrideAttr>()) | |||
6109 | HasMethodWithOverrideControl = true; | |||
6110 | else if (M->size_overridden_methods() > 0) | |||
6111 | HasOverridingMethodWithoutOverrideControl = true; | |||
6112 | // Check whether the explicitly-defaulted special members are valid. | |||
6113 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) | |||
6114 | CheckExplicitlyDefaultedSpecialMember(M); | |||
6115 | ||||
6116 | // For an explicitly defaulted or deleted special member, we defer | |||
6117 | // determining triviality until the class is complete. That time is now! | |||
6118 | CXXSpecialMember CSM = getSpecialMember(M); | |||
6119 | if (!M->isImplicit() && !M->isUserProvided()) { | |||
6120 | if (CSM != CXXInvalid) { | |||
6121 | M->setTrivial(SpecialMemberIsTrivial(M, CSM)); | |||
6122 | // Inform the class that we've finished declaring this member. | |||
6123 | Record->finishedDefaultedOrDeletedMember(M); | |||
6124 | M->setTrivialForCall( | |||
6125 | HasTrivialABI || | |||
6126 | SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); | |||
6127 | Record->setTrivialForCallFlags(M); | |||
6128 | } | |||
6129 | } | |||
6130 | ||||
6131 | // Set triviality for the purpose of calls if this is a user-provided | |||
6132 | // copy/move constructor or destructor. | |||
6133 | if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || | |||
6134 | CSM == CXXDestructor) && M->isUserProvided()) { | |||
6135 | M->setTrivialForCall(HasTrivialABI); | |||
6136 | Record->setTrivialForCallFlags(M); | |||
6137 | } | |||
6138 | ||||
6139 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && | |||
6140 | M->hasAttr<DLLExportAttr>()) { | |||
6141 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
6142 | M->isTrivial() && | |||
6143 | (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || | |||
6144 | CSM == CXXDestructor)) | |||
6145 | M->dropAttr<DLLExportAttr>(); | |||
6146 | ||||
6147 | if (M->hasAttr<DLLExportAttr>()) { | |||
6148 | DefineImplicitSpecialMember(*this, M, M->getLocation()); | |||
6149 | ActOnFinishInlineFunctionDef(M); | |||
6150 | } | |||
6151 | } | |||
6152 | } | |||
6153 | } | |||
6154 | ||||
6155 | if (HasMethodWithOverrideControl && | |||
6156 | HasOverridingMethodWithoutOverrideControl) { | |||
6157 | // At least one method has the 'override' control declared. | |||
6158 | // Diagnose all other overridden methods which do not have 'override' specified on them. | |||
6159 | for (auto *M : Record->methods()) | |||
6160 | DiagnoseAbsenceOfOverrideControl(M); | |||
6161 | } | |||
6162 | ||||
6163 | // ms_struct is a request to use the same ABI rules as MSVC. Check | |||
6164 | // whether this class uses any C++ features that are implemented | |||
6165 | // completely differently in MSVC, and if so, emit a diagnostic. | |||
6166 | // That diagnostic defaults to an error, but we allow projects to | |||
6167 | // map it down to a warning (or ignore it). It's a fairly common | |||
6168 | // practice among users of the ms_struct pragma to mass-annotate | |||
6169 | // headers, sweeping up a bunch of types that the project doesn't | |||
6170 | // really rely on MSVC-compatible layout for. We must therefore | |||
6171 | // support "ms_struct except for C++ stuff" as a secondary ABI. | |||
6172 | if (Record->isMsStruct(Context) && | |||
6173 | (Record->isPolymorphic() || Record->getNumBases())) { | |||
6174 | Diag(Record->getLocation(), diag::warn_cxx_ms_struct); | |||
6175 | } | |||
6176 | ||||
6177 | checkClassLevelDLLAttribute(Record); | |||
6178 | checkClassLevelCodeSegAttribute(Record); | |||
6179 | ||||
6180 | bool ClangABICompat4 = | |||
6181 | Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; | |||
6182 | TargetInfo::CallingConvKind CCK = | |||
6183 | Context.getTargetInfo().getCallingConvKind(ClangABICompat4); | |||
6184 | bool CanPass = canPassInRegisters(*this, Record, CCK); | |||
6185 | ||||
6186 | // Do not change ArgPassingRestrictions if it has already been set to | |||
6187 | // APK_CanNeverPassInRegs. | |||
6188 | if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) | |||
6189 | Record->setArgPassingRestrictions(CanPass | |||
6190 | ? RecordDecl::APK_CanPassInRegs | |||
6191 | : RecordDecl::APK_CannotPassInRegs); | |||
6192 | ||||
6193 | // If canPassInRegisters returns true despite the record having a non-trivial | |||
6194 | // destructor, the record is destructed in the callee. This happens only when | |||
6195 | // the record or one of its subobjects has a field annotated with trivial_abi | |||
6196 | // or a field qualified with ObjC __strong/__weak. | |||
6197 | if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) | |||
6198 | Record->setParamDestroyedInCallee(true); | |||
6199 | else if (Record->hasNonTrivialDestructor()) | |||
6200 | Record->setParamDestroyedInCallee(CanPass); | |||
6201 | ||||
6202 | if (getLangOpts().ForceEmitVTables) { | |||
6203 | // If we want to emit all the vtables, we need to mark it as used. This | |||
6204 | // is especially required for cases like vtable assumption loads. | |||
6205 | MarkVTableUsed(Record->getInnerLocStart(), Record); | |||
6206 | } | |||
6207 | } | |||
6208 | ||||
6209 | /// Look up the special member function that would be called by a special | |||
6210 | /// member function for a subobject of class type. | |||
6211 | /// | |||
6212 | /// \param Class The class type of the subobject. | |||
6213 | /// \param CSM The kind of special member function. | |||
6214 | /// \param FieldQuals If the subobject is a field, its cv-qualifiers. | |||
6215 | /// \param ConstRHS True if this is a copy operation with a const object | |||
6216 | /// on its RHS, that is, if the argument to the outer special member | |||
6217 | /// function is 'const' and this is not a field marked 'mutable'. | |||
6218 | static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( | |||
6219 | Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, | |||
6220 | unsigned FieldQuals, bool ConstRHS) { | |||
6221 | unsigned LHSQuals = 0; | |||
6222 | if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) | |||
6223 | LHSQuals = FieldQuals; | |||
6224 | ||||
6225 | unsigned RHSQuals = FieldQuals; | |||
6226 | if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) | |||
6227 | RHSQuals = 0; | |||
6228 | else if (ConstRHS) | |||
6229 | RHSQuals |= Qualifiers::Const; | |||
6230 | ||||
6231 | return S.LookupSpecialMember(Class, CSM, | |||
6232 | RHSQuals & Qualifiers::Const, | |||
6233 | RHSQuals & Qualifiers::Volatile, | |||
6234 | false, | |||
6235 | LHSQuals & Qualifiers::Const, | |||
6236 | LHSQuals & Qualifiers::Volatile); | |||
6237 | } | |||
6238 | ||||
6239 | class Sema::InheritedConstructorInfo { | |||
6240 | Sema &S; | |||
6241 | SourceLocation UseLoc; | |||
6242 | ||||
6243 | /// A mapping from the base classes through which the constructor was | |||
6244 | /// inherited to the using shadow declaration in that base class (or a null | |||
6245 | /// pointer if the constructor was declared in that base class). | |||
6246 | llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> | |||
6247 | InheritedFromBases; | |||
6248 | ||||
6249 | public: | |||
6250 | InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, | |||
6251 | ConstructorUsingShadowDecl *Shadow) | |||
6252 | : S(S), UseLoc(UseLoc) { | |||
6253 | bool DiagnosedMultipleConstructedBases = false; | |||
6254 | CXXRecordDecl *ConstructedBase = nullptr; | |||
6255 | UsingDecl *ConstructedBaseUsing = nullptr; | |||
6256 | ||||
6257 | // Find the set of such base class subobjects and check that there's a | |||
6258 | // unique constructed subobject. | |||
6259 | for (auto *D : Shadow->redecls()) { | |||
6260 | auto *DShadow = cast<ConstructorUsingShadowDecl>(D); | |||
6261 | auto *DNominatedBase = DShadow->getNominatedBaseClass(); | |||
6262 | auto *DConstructedBase = DShadow->getConstructedBaseClass(); | |||
6263 | ||||
6264 | InheritedFromBases.insert( | |||
6265 | std::make_pair(DNominatedBase->getCanonicalDecl(), | |||
6266 | DShadow->getNominatedBaseClassShadowDecl())); | |||
6267 | if (DShadow->constructsVirtualBase()) | |||
6268 | InheritedFromBases.insert( | |||
6269 | std::make_pair(DConstructedBase->getCanonicalDecl(), | |||
6270 | DShadow->getConstructedBaseClassShadowDecl())); | |||
6271 | else | |||
6272 | assert(DNominatedBase == DConstructedBase)((DNominatedBase == DConstructedBase) ? static_cast<void> (0) : __assert_fail ("DNominatedBase == DConstructedBase", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6272, __PRETTY_FUNCTION__)); | |||
6273 | ||||
6274 | // [class.inhctor.init]p2: | |||
6275 | // If the constructor was inherited from multiple base class subobjects | |||
6276 | // of type B, the program is ill-formed. | |||
6277 | if (!ConstructedBase) { | |||
6278 | ConstructedBase = DConstructedBase; | |||
6279 | ConstructedBaseUsing = D->getUsingDecl(); | |||
6280 | } else if (ConstructedBase != DConstructedBase && | |||
6281 | !Shadow->isInvalidDecl()) { | |||
6282 | if (!DiagnosedMultipleConstructedBases) { | |||
6283 | S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) | |||
6284 | << Shadow->getTargetDecl(); | |||
6285 | S.Diag(ConstructedBaseUsing->getLocation(), | |||
6286 | diag::note_ambiguous_inherited_constructor_using) | |||
6287 | << ConstructedBase; | |||
6288 | DiagnosedMultipleConstructedBases = true; | |||
6289 | } | |||
6290 | S.Diag(D->getUsingDecl()->getLocation(), | |||
6291 | diag::note_ambiguous_inherited_constructor_using) | |||
6292 | << DConstructedBase; | |||
6293 | } | |||
6294 | } | |||
6295 | ||||
6296 | if (DiagnosedMultipleConstructedBases) | |||
6297 | Shadow->setInvalidDecl(); | |||
6298 | } | |||
6299 | ||||
6300 | /// Find the constructor to use for inherited construction of a base class, | |||
6301 | /// and whether that base class constructor inherits the constructor from a | |||
6302 | /// virtual base class (in which case it won't actually invoke it). | |||
6303 | std::pair<CXXConstructorDecl *, bool> | |||
6304 | findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { | |||
6305 | auto It = InheritedFromBases.find(Base->getCanonicalDecl()); | |||
6306 | if (It == InheritedFromBases.end()) | |||
6307 | return std::make_pair(nullptr, false); | |||
6308 | ||||
6309 | // This is an intermediary class. | |||
6310 | if (It->second) | |||
6311 | return std::make_pair( | |||
6312 | S.findInheritingConstructor(UseLoc, Ctor, It->second), | |||
6313 | It->second->constructsVirtualBase()); | |||
6314 | ||||
6315 | // This is the base class from which the constructor was inherited. | |||
6316 | return std::make_pair(Ctor, false); | |||
6317 | } | |||
6318 | }; | |||
6319 | ||||
6320 | /// Is the special member function which would be selected to perform the | |||
6321 | /// specified operation on the specified class type a constexpr constructor? | |||
6322 | static bool | |||
6323 | specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, | |||
6324 | Sema::CXXSpecialMember CSM, unsigned Quals, | |||
6325 | bool ConstRHS, | |||
6326 | CXXConstructorDecl *InheritedCtor = nullptr, | |||
6327 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | |||
6328 | // If we're inheriting a constructor, see if we need to call it for this base | |||
6329 | // class. | |||
6330 | if (InheritedCtor) { | |||
6331 | assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void> (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6331, __PRETTY_FUNCTION__)); | |||
6332 | auto BaseCtor = | |||
6333 | Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; | |||
6334 | if (BaseCtor) | |||
6335 | return BaseCtor->isConstexpr(); | |||
6336 | } | |||
6337 | ||||
6338 | if (CSM == Sema::CXXDefaultConstructor) | |||
6339 | return ClassDecl->hasConstexprDefaultConstructor(); | |||
6340 | ||||
6341 | Sema::SpecialMemberOverloadResult SMOR = | |||
6342 | lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); | |||
6343 | if (!SMOR.getMethod()) | |||
6344 | // A constructor we wouldn't select can't be "involved in initializing" | |||
6345 | // anything. | |||
6346 | return true; | |||
6347 | return SMOR.getMethod()->isConstexpr(); | |||
6348 | } | |||
6349 | ||||
6350 | /// Determine whether the specified special member function would be constexpr | |||
6351 | /// if it were implicitly defined. | |||
6352 | static bool defaultedSpecialMemberIsConstexpr( | |||
6353 | Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, | |||
6354 | bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, | |||
6355 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | |||
6356 | if (!S.getLangOpts().CPlusPlus11) | |||
6357 | return false; | |||
6358 | ||||
6359 | // C++11 [dcl.constexpr]p4: | |||
6360 | // In the definition of a constexpr constructor [...] | |||
6361 | bool Ctor = true; | |||
6362 | switch (CSM) { | |||
6363 | case Sema::CXXDefaultConstructor: | |||
6364 | if (Inherited) | |||
6365 | break; | |||
6366 | // Since default constructor lookup is essentially trivial (and cannot | |||
6367 | // involve, for instance, template instantiation), we compute whether a | |||
6368 | // defaulted default constructor is constexpr directly within CXXRecordDecl. | |||
6369 | // | |||
6370 | // This is important for performance; we need to know whether the default | |||
6371 | // constructor is constexpr to determine whether the type is a literal type. | |||
6372 | return ClassDecl->defaultedDefaultConstructorIsConstexpr(); | |||
6373 | ||||
6374 | case Sema::CXXCopyConstructor: | |||
6375 | case Sema::CXXMoveConstructor: | |||
6376 | // For copy or move constructors, we need to perform overload resolution. | |||
6377 | break; | |||
6378 | ||||
6379 | case Sema::CXXCopyAssignment: | |||
6380 | case Sema::CXXMoveAssignment: | |||
6381 | if (!S.getLangOpts().CPlusPlus14) | |||
6382 | return false; | |||
6383 | // In C++1y, we need to perform overload resolution. | |||
6384 | Ctor = false; | |||
6385 | break; | |||
6386 | ||||
6387 | case Sema::CXXDestructor: | |||
6388 | case Sema::CXXInvalid: | |||
6389 | return false; | |||
6390 | } | |||
6391 | ||||
6392 | // -- if the class is a non-empty union, or for each non-empty anonymous | |||
6393 | // union member of a non-union class, exactly one non-static data member | |||
6394 | // shall be initialized; [DR1359] | |||
6395 | // | |||
6396 | // If we squint, this is guaranteed, since exactly one non-static data member | |||
6397 | // will be initialized (if the constructor isn't deleted), we just don't know | |||
6398 | // which one. | |||
6399 | if (Ctor && ClassDecl->isUnion()) | |||
6400 | return CSM == Sema::CXXDefaultConstructor | |||
6401 | ? ClassDecl->hasInClassInitializer() || | |||
6402 | !ClassDecl->hasVariantMembers() | |||
6403 | : true; | |||
6404 | ||||
6405 | // -- the class shall not have any virtual base classes; | |||
6406 | if (Ctor && ClassDecl->getNumVBases()) | |||
6407 | return false; | |||
6408 | ||||
6409 | // C++1y [class.copy]p26: | |||
6410 | // -- [the class] is a literal type, and | |||
6411 | if (!Ctor && !ClassDecl->isLiteral()) | |||
6412 | return false; | |||
6413 | ||||
6414 | // -- every constructor involved in initializing [...] base class | |||
6415 | // sub-objects shall be a constexpr constructor; | |||
6416 | // -- the assignment operator selected to copy/move each direct base | |||
6417 | // class is a constexpr function, and | |||
6418 | for (const auto &B : ClassDecl->bases()) { | |||
6419 | const RecordType *BaseType = B.getType()->getAs<RecordType>(); | |||
6420 | if (!BaseType) continue; | |||
6421 | ||||
6422 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); | |||
6423 | if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, | |||
6424 | InheritedCtor, Inherited)) | |||
6425 | return false; | |||
6426 | } | |||
6427 | ||||
6428 | // -- every constructor involved in initializing non-static data members | |||
6429 | // [...] shall be a constexpr constructor; | |||
6430 | // -- every non-static data member and base class sub-object shall be | |||
6431 | // initialized | |||
6432 | // -- for each non-static data member of X that is of class type (or array | |||
6433 | // thereof), the assignment operator selected to copy/move that member is | |||
6434 | // a constexpr function | |||
6435 | for (const auto *F : ClassDecl->fields()) { | |||
6436 | if (F->isInvalidDecl()) | |||
6437 | continue; | |||
6438 | if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) | |||
6439 | continue; | |||
6440 | QualType BaseType = S.Context.getBaseElementType(F->getType()); | |||
6441 | if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { | |||
6442 | CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
6443 | if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, | |||
6444 | BaseType.getCVRQualifiers(), | |||
6445 | ConstArg && !F->isMutable())) | |||
6446 | return false; | |||
6447 | } else if (CSM == Sema::CXXDefaultConstructor) { | |||
6448 | return false; | |||
6449 | } | |||
6450 | } | |||
6451 | ||||
6452 | // All OK, it's constexpr! | |||
6453 | return true; | |||
6454 | } | |||
6455 | ||||
6456 | static Sema::ImplicitExceptionSpecification | |||
6457 | ComputeDefaultedSpecialMemberExceptionSpec( | |||
6458 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
6459 | Sema::InheritedConstructorInfo *ICI); | |||
6460 | ||||
6461 | static Sema::ImplicitExceptionSpecification | |||
6462 | computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { | |||
6463 | auto CSM = S.getSpecialMember(MD); | |||
6464 | if (CSM != Sema::CXXInvalid) | |||
6465 | return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); | |||
6466 | ||||
6467 | auto *CD = cast<CXXConstructorDecl>(MD); | |||
6468 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6469, __PRETTY_FUNCTION__)) | |||
6469 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6469, __PRETTY_FUNCTION__)); | |||
6470 | Sema::InheritedConstructorInfo ICI( | |||
6471 | S, Loc, CD->getInheritedConstructor().getShadowDecl()); | |||
6472 | return ComputeDefaultedSpecialMemberExceptionSpec( | |||
6473 | S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); | |||
6474 | } | |||
6475 | ||||
6476 | static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, | |||
6477 | CXXMethodDecl *MD) { | |||
6478 | FunctionProtoType::ExtProtoInfo EPI; | |||
6479 | ||||
6480 | // Build an exception specification pointing back at this member. | |||
6481 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
6482 | EPI.ExceptionSpec.SourceDecl = MD; | |||
6483 | ||||
6484 | // Set the calling convention to the default for C++ instance methods. | |||
6485 | EPI.ExtInfo = EPI.ExtInfo.withCallingConv( | |||
6486 | S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, | |||
6487 | /*IsCXXMethod=*/true)); | |||
6488 | return EPI; | |||
6489 | } | |||
6490 | ||||
6491 | void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { | |||
6492 | const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); | |||
6493 | if (FPT->getExceptionSpecType() != EST_Unevaluated) | |||
6494 | return; | |||
6495 | ||||
6496 | // Evaluate the exception specification. | |||
6497 | auto IES = computeImplicitExceptionSpec(*this, Loc, MD); | |||
6498 | auto ESI = IES.getExceptionSpec(); | |||
6499 | ||||
6500 | // Update the type of the special member to use it. | |||
6501 | UpdateExceptionSpec(MD, ESI); | |||
6502 | ||||
6503 | // A user-provided destructor can be defined outside the class. When that | |||
6504 | // happens, be sure to update the exception specification on both | |||
6505 | // declarations. | |||
6506 | const FunctionProtoType *CanonicalFPT = | |||
6507 | MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); | |||
6508 | if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) | |||
6509 | UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); | |||
6510 | } | |||
6511 | ||||
6512 | void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { | |||
6513 | CXXRecordDecl *RD = MD->getParent(); | |||
6514 | CXXSpecialMember CSM = getSpecialMember(MD); | |||
6515 | ||||
6516 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6517, __PRETTY_FUNCTION__)) | |||
6517 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6517, __PRETTY_FUNCTION__)); | |||
6518 | ||||
6519 | // Whether this was the first-declared instance of the constructor. | |||
6520 | // This affects whether we implicitly add an exception spec and constexpr. | |||
6521 | bool First = MD == MD->getCanonicalDecl(); | |||
6522 | ||||
6523 | bool HadError = false; | |||
6524 | ||||
6525 | // C++11 [dcl.fct.def.default]p1: | |||
6526 | // A function that is explicitly defaulted shall | |||
6527 | // -- be a special member function (checked elsewhere), | |||
6528 | // -- have the same type (except for ref-qualifiers, and except that a | |||
6529 | // copy operation can take a non-const reference) as an implicit | |||
6530 | // declaration, and | |||
6531 | // -- not have default arguments. | |||
6532 | // C++2a changes the second bullet to instead delete the function if it's | |||
6533 | // defaulted on its first declaration, unless it's "an assignment operator, | |||
6534 | // and its return type differs or its parameter type is not a reference". | |||
6535 | bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; | |||
6536 | bool ShouldDeleteForTypeMismatch = false; | |||
6537 | unsigned ExpectedParams = 1; | |||
6538 | if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) | |||
6539 | ExpectedParams = 0; | |||
6540 | if (MD->getNumParams() != ExpectedParams) { | |||
6541 | // This checks for default arguments: a copy or move constructor with a | |||
6542 | // default argument is classified as a default constructor, and assignment | |||
6543 | // operations and destructors can't have default arguments. | |||
6544 | Diag(MD->getLocation(), diag::err_defaulted_special_member_params) | |||
6545 | << CSM << MD->getSourceRange(); | |||
6546 | HadError = true; | |||
6547 | } else if (MD->isVariadic()) { | |||
6548 | if (DeleteOnTypeMismatch) | |||
6549 | ShouldDeleteForTypeMismatch = true; | |||
6550 | else { | |||
6551 | Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) | |||
6552 | << CSM << MD->getSourceRange(); | |||
6553 | HadError = true; | |||
6554 | } | |||
6555 | } | |||
6556 | ||||
6557 | const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); | |||
6558 | ||||
6559 | bool CanHaveConstParam = false; | |||
6560 | if (CSM == CXXCopyConstructor) | |||
6561 | CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); | |||
6562 | else if (CSM == CXXCopyAssignment) | |||
6563 | CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); | |||
6564 | ||||
6565 | QualType ReturnType = Context.VoidTy; | |||
6566 | if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { | |||
6567 | // Check for return type matching. | |||
6568 | ReturnType = Type->getReturnType(); | |||
6569 | ||||
6570 | QualType DeclType = Context.getTypeDeclType(RD); | |||
6571 | DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); | |||
6572 | QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); | |||
6573 | ||||
6574 | if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { | |||
6575 | Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) | |||
6576 | << (CSM == CXXMoveAssignment) << ExpectedReturnType; | |||
6577 | HadError = true; | |||
6578 | } | |||
6579 | ||||
6580 | // A defaulted special member cannot have cv-qualifiers. | |||
6581 | if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { | |||
6582 | if (DeleteOnTypeMismatch) | |||
6583 | ShouldDeleteForTypeMismatch = true; | |||
6584 | else { | |||
6585 | Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) | |||
6586 | << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; | |||
6587 | HadError = true; | |||
6588 | } | |||
6589 | } | |||
6590 | } | |||
6591 | ||||
6592 | // Check for parameter type matching. | |||
6593 | QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); | |||
6594 | bool HasConstParam = false; | |||
6595 | if (ExpectedParams && ArgType->isReferenceType()) { | |||
6596 | // Argument must be reference to possibly-const T. | |||
6597 | QualType ReferentType = ArgType->getPointeeType(); | |||
6598 | HasConstParam = ReferentType.isConstQualified(); | |||
6599 | ||||
6600 | if (ReferentType.isVolatileQualified()) { | |||
6601 | if (DeleteOnTypeMismatch) | |||
6602 | ShouldDeleteForTypeMismatch = true; | |||
6603 | else { | |||
6604 | Diag(MD->getLocation(), | |||
6605 | diag::err_defaulted_special_member_volatile_param) << CSM; | |||
6606 | HadError = true; | |||
6607 | } | |||
6608 | } | |||
6609 | ||||
6610 | if (HasConstParam && !CanHaveConstParam) { | |||
6611 | if (DeleteOnTypeMismatch) | |||
6612 | ShouldDeleteForTypeMismatch = true; | |||
6613 | else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { | |||
6614 | Diag(MD->getLocation(), | |||
6615 | diag::err_defaulted_special_member_copy_const_param) | |||
6616 | << (CSM == CXXCopyAssignment); | |||
6617 | // FIXME: Explain why this special member can't be const. | |||
6618 | HadError = true; | |||
6619 | } else { | |||
6620 | Diag(MD->getLocation(), | |||
6621 | diag::err_defaulted_special_member_move_const_param) | |||
6622 | << (CSM == CXXMoveAssignment); | |||
6623 | HadError = true; | |||
6624 | } | |||
6625 | } | |||
6626 | } else if (ExpectedParams) { | |||
6627 | // A copy assignment operator can take its argument by value, but a | |||
6628 | // defaulted one cannot. | |||
6629 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6629, __PRETTY_FUNCTION__)); | |||
6630 | Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); | |||
6631 | HadError = true; | |||
6632 | } | |||
6633 | ||||
6634 | // C++11 [dcl.fct.def.default]p2: | |||
6635 | // An explicitly-defaulted function may be declared constexpr only if it | |||
6636 | // would have been implicitly declared as constexpr, | |||
6637 | // Do not apply this rule to members of class templates, since core issue 1358 | |||
6638 | // makes such functions always instantiate to constexpr functions. For | |||
6639 | // functions which cannot be constexpr (for non-constructors in C++11 and for | |||
6640 | // destructors in C++1y), this is checked elsewhere. | |||
6641 | // | |||
6642 | // FIXME: This should not apply if the member is deleted. | |||
6643 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, | |||
6644 | HasConstParam); | |||
6645 | if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) | |||
6646 | : isa<CXXConstructorDecl>(MD)) && | |||
6647 | MD->isConstexpr() && !Constexpr && | |||
6648 | MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { | |||
6649 | Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM; | |||
6650 | // FIXME: Explain why the special member can't be constexpr. | |||
6651 | HadError = true; | |||
6652 | } | |||
6653 | ||||
6654 | if (First) { | |||
6655 | // C++2a [dcl.fct.def.default]p3: | |||
6656 | // If a function is explicitly defaulted on its first declaration, it is | |||
6657 | // implicitly considered to be constexpr if the implicit declaration | |||
6658 | // would be. | |||
6659 | MD->setConstexpr(Constexpr); | |||
6660 | ||||
6661 | if (!Type->hasExceptionSpec()) { | |||
6662 | // C++2a [except.spec]p3: | |||
6663 | // If a declaration of a function does not have a noexcept-specifier | |||
6664 | // [and] is defaulted on its first declaration, [...] the exception | |||
6665 | // specification is as specified below | |||
6666 | FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); | |||
6667 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
6668 | EPI.ExceptionSpec.SourceDecl = MD; | |||
6669 | MD->setType(Context.getFunctionType(ReturnType, | |||
6670 | llvm::makeArrayRef(&ArgType, | |||
6671 | ExpectedParams), | |||
6672 | EPI)); | |||
6673 | } | |||
6674 | } | |||
6675 | ||||
6676 | if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { | |||
6677 | if (First) { | |||
6678 | SetDeclDeleted(MD, MD->getLocation()); | |||
6679 | if (!inTemplateInstantiation() && !HadError) { | |||
6680 | Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; | |||
6681 | if (ShouldDeleteForTypeMismatch) { | |||
6682 | Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; | |||
6683 | } else { | |||
6684 | ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); | |||
6685 | } | |||
6686 | } | |||
6687 | if (ShouldDeleteForTypeMismatch && !HadError) { | |||
6688 | Diag(MD->getLocation(), | |||
6689 | diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; | |||
6690 | } | |||
6691 | } else { | |||
6692 | // C++11 [dcl.fct.def.default]p4: | |||
6693 | // [For a] user-provided explicitly-defaulted function [...] if such a | |||
6694 | // function is implicitly defined as deleted, the program is ill-formed. | |||
6695 | Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; | |||
6696 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6696, __PRETTY_FUNCTION__)); | |||
6697 | ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); | |||
6698 | HadError = true; | |||
6699 | } | |||
6700 | } | |||
6701 | ||||
6702 | if (HadError) | |||
6703 | MD->setInvalidDecl(); | |||
6704 | } | |||
6705 | ||||
6706 | void Sema::CheckDelayedMemberExceptionSpecs() { | |||
6707 | decltype(DelayedOverridingExceptionSpecChecks) Overriding; | |||
6708 | decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; | |||
6709 | ||||
6710 | std::swap(Overriding, DelayedOverridingExceptionSpecChecks); | |||
6711 | std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); | |||
6712 | ||||
6713 | // Perform any deferred checking of exception specifications for virtual | |||
6714 | // destructors. | |||
6715 | for (auto &Check : Overriding) | |||
6716 | CheckOverridingFunctionExceptionSpec(Check.first, Check.second); | |||
6717 | ||||
6718 | // Perform any deferred checking of exception specifications for befriended | |||
6719 | // special members. | |||
6720 | for (auto &Check : Equivalent) | |||
6721 | CheckEquivalentExceptionSpec(Check.second, Check.first); | |||
6722 | } | |||
6723 | ||||
6724 | namespace { | |||
6725 | /// CRTP base class for visiting operations performed by a special member | |||
6726 | /// function (or inherited constructor). | |||
6727 | template<typename Derived> | |||
6728 | struct SpecialMemberVisitor { | |||
6729 | Sema &S; | |||
6730 | CXXMethodDecl *MD; | |||
6731 | Sema::CXXSpecialMember CSM; | |||
6732 | Sema::InheritedConstructorInfo *ICI; | |||
6733 | ||||
6734 | // Properties of the special member, computed for convenience. | |||
6735 | bool IsConstructor = false, IsAssignment = false, ConstArg = false; | |||
6736 | ||||
6737 | SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
6738 | Sema::InheritedConstructorInfo *ICI) | |||
6739 | : S(S), MD(MD), CSM(CSM), ICI(ICI) { | |||
6740 | switch (CSM) { | |||
6741 | case Sema::CXXDefaultConstructor: | |||
6742 | case Sema::CXXCopyConstructor: | |||
6743 | case Sema::CXXMoveConstructor: | |||
6744 | IsConstructor = true; | |||
6745 | break; | |||
6746 | case Sema::CXXCopyAssignment: | |||
6747 | case Sema::CXXMoveAssignment: | |||
6748 | IsAssignment = true; | |||
6749 | break; | |||
6750 | case Sema::CXXDestructor: | |||
6751 | break; | |||
6752 | case Sema::CXXInvalid: | |||
6753 | llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6753); | |||
6754 | } | |||
6755 | ||||
6756 | if (MD->getNumParams()) { | |||
6757 | if (const ReferenceType *RT = | |||
6758 | MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) | |||
6759 | ConstArg = RT->getPointeeType().isConstQualified(); | |||
6760 | } | |||
6761 | } | |||
6762 | ||||
6763 | Derived &getDerived() { return static_cast<Derived&>(*this); } | |||
6764 | ||||
6765 | /// Is this a "move" special member? | |||
6766 | bool isMove() const { | |||
6767 | return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; | |||
6768 | } | |||
6769 | ||||
6770 | /// Look up the corresponding special member in the given class. | |||
6771 | Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, | |||
6772 | unsigned Quals, bool IsMutable) { | |||
6773 | return lookupCallFromSpecialMember(S, Class, CSM, Quals, | |||
6774 | ConstArg && !IsMutable); | |||
6775 | } | |||
6776 | ||||
6777 | /// Look up the constructor for the specified base class to see if it's | |||
6778 | /// overridden due to this being an inherited constructor. | |||
6779 | Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { | |||
6780 | if (!ICI) | |||
6781 | return {}; | |||
6782 | assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void> (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6782, __PRETTY_FUNCTION__)); | |||
6783 | auto *BaseCtor = | |||
6784 | cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); | |||
6785 | if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) | |||
6786 | return MD; | |||
6787 | return {}; | |||
6788 | } | |||
6789 | ||||
6790 | /// A base or member subobject. | |||
6791 | typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; | |||
6792 | ||||
6793 | /// Get the location to use for a subobject in diagnostics. | |||
6794 | static SourceLocation getSubobjectLoc(Subobject Subobj) { | |||
6795 | // FIXME: For an indirect virtual base, the direct base leading to | |||
6796 | // the indirect virtual base would be a more useful choice. | |||
6797 | if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) | |||
6798 | return B->getBaseTypeLoc(); | |||
6799 | else | |||
6800 | return Subobj.get<FieldDecl*>()->getLocation(); | |||
6801 | } | |||
6802 | ||||
6803 | enum BasesToVisit { | |||
6804 | /// Visit all non-virtual (direct) bases. | |||
6805 | VisitNonVirtualBases, | |||
6806 | /// Visit all direct bases, virtual or not. | |||
6807 | VisitDirectBases, | |||
6808 | /// Visit all non-virtual bases, and all virtual bases if the class | |||
6809 | /// is not abstract. | |||
6810 | VisitPotentiallyConstructedBases, | |||
6811 | /// Visit all direct or virtual bases. | |||
6812 | VisitAllBases | |||
6813 | }; | |||
6814 | ||||
6815 | // Visit the bases and members of the class. | |||
6816 | bool visit(BasesToVisit Bases) { | |||
6817 | CXXRecordDecl *RD = MD->getParent(); | |||
6818 | ||||
6819 | if (Bases == VisitPotentiallyConstructedBases) | |||
6820 | Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; | |||
6821 | ||||
6822 | for (auto &B : RD->bases()) | |||
6823 | if ((Bases == VisitDirectBases || !B.isVirtual()) && | |||
6824 | getDerived().visitBase(&B)) | |||
6825 | return true; | |||
6826 | ||||
6827 | if (Bases == VisitAllBases) | |||
6828 | for (auto &B : RD->vbases()) | |||
6829 | if (getDerived().visitBase(&B)) | |||
6830 | return true; | |||
6831 | ||||
6832 | for (auto *F : RD->fields()) | |||
6833 | if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && | |||
6834 | getDerived().visitField(F)) | |||
6835 | return true; | |||
6836 | ||||
6837 | return false; | |||
6838 | } | |||
6839 | }; | |||
6840 | } | |||
6841 | ||||
6842 | namespace { | |||
6843 | struct SpecialMemberDeletionInfo | |||
6844 | : SpecialMemberVisitor<SpecialMemberDeletionInfo> { | |||
6845 | bool Diagnose; | |||
6846 | ||||
6847 | SourceLocation Loc; | |||
6848 | ||||
6849 | bool AllFieldsAreConst; | |||
6850 | ||||
6851 | SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, | |||
6852 | Sema::CXXSpecialMember CSM, | |||
6853 | Sema::InheritedConstructorInfo *ICI, bool Diagnose) | |||
6854 | : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), | |||
6855 | Loc(MD->getLocation()), AllFieldsAreConst(true) {} | |||
6856 | ||||
6857 | bool inUnion() const { return MD->getParent()->isUnion(); } | |||
6858 | ||||
6859 | Sema::CXXSpecialMember getEffectiveCSM() { | |||
6860 | return ICI ? Sema::CXXInvalid : CSM; | |||
6861 | } | |||
6862 | ||||
6863 | bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); | |||
6864 | ||||
6865 | bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } | |||
6866 | bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } | |||
6867 | ||||
6868 | bool shouldDeleteForBase(CXXBaseSpecifier *Base); | |||
6869 | bool shouldDeleteForField(FieldDecl *FD); | |||
6870 | bool shouldDeleteForAllConstMembers(); | |||
6871 | ||||
6872 | bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | |||
6873 | unsigned Quals); | |||
6874 | bool shouldDeleteForSubobjectCall(Subobject Subobj, | |||
6875 | Sema::SpecialMemberOverloadResult SMOR, | |||
6876 | bool IsDtorCallInCtor); | |||
6877 | ||||
6878 | bool isAccessible(Subobject Subobj, CXXMethodDecl *D); | |||
6879 | }; | |||
6880 | } | |||
6881 | ||||
6882 | /// Is the given special member inaccessible when used on the given | |||
6883 | /// sub-object. | |||
6884 | bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, | |||
6885 | CXXMethodDecl *target) { | |||
6886 | /// If we're operating on a base class, the object type is the | |||
6887 | /// type of this special member. | |||
6888 | QualType objectTy; | |||
6889 | AccessSpecifier access = target->getAccess(); | |||
6890 | if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { | |||
6891 | objectTy = S.Context.getTypeDeclType(MD->getParent()); | |||
6892 | access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); | |||
6893 | ||||
6894 | // If we're operating on a field, the object type is the type of the field. | |||
6895 | } else { | |||
6896 | objectTy = S.Context.getTypeDeclType(target->getParent()); | |||
6897 | } | |||
6898 | ||||
6899 | return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); | |||
6900 | } | |||
6901 | ||||
6902 | /// Check whether we should delete a special member due to the implicit | |||
6903 | /// definition containing a call to a special member of a subobject. | |||
6904 | bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( | |||
6905 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, | |||
6906 | bool IsDtorCallInCtor) { | |||
6907 | CXXMethodDecl *Decl = SMOR.getMethod(); | |||
6908 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
6909 | ||||
6910 | int DiagKind = -1; | |||
6911 | ||||
6912 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) | |||
6913 | DiagKind = !Decl ? 0 : 1; | |||
6914 | else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | |||
6915 | DiagKind = 2; | |||
6916 | else if (!isAccessible(Subobj, Decl)) | |||
6917 | DiagKind = 3; | |||
6918 | else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && | |||
6919 | !Decl->isTrivial()) { | |||
6920 | // A member of a union must have a trivial corresponding special member. | |||
6921 | // As a weird special case, a destructor call from a union's constructor | |||
6922 | // must be accessible and non-deleted, but need not be trivial. Such a | |||
6923 | // destructor is never actually called, but is semantically checked as | |||
6924 | // if it were. | |||
6925 | DiagKind = 4; | |||
6926 | } | |||
6927 | ||||
6928 | if (DiagKind == -1) | |||
6929 | return false; | |||
6930 | ||||
6931 | if (Diagnose) { | |||
6932 | if (Field) { | |||
6933 | S.Diag(Field->getLocation(), | |||
6934 | diag::note_deleted_special_member_class_subobject) | |||
6935 | << getEffectiveCSM() << MD->getParent() << /*IsField*/true | |||
6936 | << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; | |||
6937 | } else { | |||
6938 | CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); | |||
6939 | S.Diag(Base->getBeginLoc(), | |||
6940 | diag::note_deleted_special_member_class_subobject) | |||
6941 | << getEffectiveCSM() << MD->getParent() << /*IsField*/ false | |||
6942 | << Base->getType() << DiagKind << IsDtorCallInCtor | |||
6943 | << /*IsObjCPtr*/false; | |||
6944 | } | |||
6945 | ||||
6946 | if (DiagKind == 1) | |||
6947 | S.NoteDeletedFunction(Decl); | |||
6948 | // FIXME: Explain inaccessibility if DiagKind == 3. | |||
6949 | } | |||
6950 | ||||
6951 | return true; | |||
6952 | } | |||
6953 | ||||
6954 | /// Check whether we should delete a special member function due to having a | |||
6955 | /// direct or virtual base class or non-static data member of class type M. | |||
6956 | bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( | |||
6957 | CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { | |||
6958 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
6959 | bool IsMutable = Field && Field->isMutable(); | |||
6960 | ||||
6961 | // C++11 [class.ctor]p5: | |||
6962 | // -- any direct or virtual base class, or non-static data member with no | |||
6963 | // brace-or-equal-initializer, has class type M (or array thereof) and | |||
6964 | // either M has no default constructor or overload resolution as applied | |||
6965 | // to M's default constructor results in an ambiguity or in a function | |||
6966 | // that is deleted or inaccessible | |||
6967 | // C++11 [class.copy]p11, C++11 [class.copy]p23: | |||
6968 | // -- a direct or virtual base class B that cannot be copied/moved because | |||
6969 | // overload resolution, as applied to B's corresponding special member, | |||
6970 | // results in an ambiguity or a function that is deleted or inaccessible | |||
6971 | // from the defaulted special member | |||
6972 | // C++11 [class.dtor]p5: | |||
6973 | // -- any direct or virtual base class [...] has a type with a destructor | |||
6974 | // that is deleted or inaccessible | |||
6975 | if (!(CSM == Sema::CXXDefaultConstructor && | |||
6976 | Field && Field->hasInClassInitializer()) && | |||
6977 | shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), | |||
6978 | false)) | |||
6979 | return true; | |||
6980 | ||||
6981 | // C++11 [class.ctor]p5, C++11 [class.copy]p11: | |||
6982 | // -- any direct or virtual base class or non-static data member has a | |||
6983 | // type with a destructor that is deleted or inaccessible | |||
6984 | if (IsConstructor) { | |||
6985 | Sema::SpecialMemberOverloadResult SMOR = | |||
6986 | S.LookupSpecialMember(Class, Sema::CXXDestructor, | |||
6987 | false, false, false, false, false); | |||
6988 | if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) | |||
6989 | return true; | |||
6990 | } | |||
6991 | ||||
6992 | return false; | |||
6993 | } | |||
6994 | ||||
6995 | bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( | |||
6996 | FieldDecl *FD, QualType FieldType) { | |||
6997 | // The defaulted special functions are defined as deleted if this is a variant | |||
6998 | // member with a non-trivial ownership type, e.g., ObjC __strong or __weak | |||
6999 | // type under ARC. | |||
7000 | if (!FieldType.hasNonTrivialObjCLifetime()) | |||
7001 | return false; | |||
7002 | ||||
7003 | // Don't make the defaulted default constructor defined as deleted if the | |||
7004 | // member has an in-class initializer. | |||
7005 | if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) | |||
7006 | return false; | |||
7007 | ||||
7008 | if (Diagnose) { | |||
7009 | auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); | |||
7010 | S.Diag(FD->getLocation(), | |||
7011 | diag::note_deleted_special_member_class_subobject) | |||
7012 | << getEffectiveCSM() << ParentClass << /*IsField*/true | |||
7013 | << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; | |||
7014 | } | |||
7015 | ||||
7016 | return true; | |||
7017 | } | |||
7018 | ||||
7019 | /// Check whether we should delete a special member function due to the class | |||
7020 | /// having a particular direct or virtual base class. | |||
7021 | bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { | |||
7022 | CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); | |||
7023 | // If program is correct, BaseClass cannot be null, but if it is, the error | |||
7024 | // must be reported elsewhere. | |||
7025 | if (!BaseClass) | |||
7026 | return false; | |||
7027 | // If we have an inheriting constructor, check whether we're calling an | |||
7028 | // inherited constructor instead of a default constructor. | |||
7029 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | |||
7030 | if (auto *BaseCtor = SMOR.getMethod()) { | |||
7031 | // Note that we do not check access along this path; other than that, | |||
7032 | // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); | |||
7033 | // FIXME: Check that the base has a usable destructor! Sink this into | |||
7034 | // shouldDeleteForClassSubobject. | |||
7035 | if (BaseCtor->isDeleted() && Diagnose) { | |||
7036 | S.Diag(Base->getBeginLoc(), | |||
7037 | diag::note_deleted_special_member_class_subobject) | |||
7038 | << getEffectiveCSM() << MD->getParent() << /*IsField*/ false | |||
7039 | << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false | |||
7040 | << /*IsObjCPtr*/false; | |||
7041 | S.NoteDeletedFunction(BaseCtor); | |||
7042 | } | |||
7043 | return BaseCtor->isDeleted(); | |||
7044 | } | |||
7045 | return shouldDeleteForClassSubobject(BaseClass, Base, 0); | |||
7046 | } | |||
7047 | ||||
7048 | /// Check whether we should delete a special member function due to the class | |||
7049 | /// having a particular non-static data member. | |||
7050 | bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { | |||
7051 | QualType FieldType = S.Context.getBaseElementType(FD->getType()); | |||
7052 | CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); | |||
7053 | ||||
7054 | if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) | |||
7055 | return true; | |||
7056 | ||||
7057 | if (CSM == Sema::CXXDefaultConstructor) { | |||
7058 | // For a default constructor, all references must be initialized in-class | |||
7059 | // and, if a union, it must have a non-const member. | |||
7060 | if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { | |||
7061 | if (Diagnose) | |||
7062 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | |||
7063 | << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; | |||
7064 | return true; | |||
7065 | } | |||
7066 | // C++11 [class.ctor]p5: any non-variant non-static data member of | |||
7067 | // const-qualified type (or array thereof) with no | |||
7068 | // brace-or-equal-initializer does not have a user-provided default | |||
7069 | // constructor. | |||
7070 | if (!inUnion() && FieldType.isConstQualified() && | |||
7071 | !FD->hasInClassInitializer() && | |||
7072 | (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { | |||
7073 | if (Diagnose) | |||
7074 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | |||
7075 | << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; | |||
7076 | return true; | |||
7077 | } | |||
7078 | ||||
7079 | if (inUnion() && !FieldType.isConstQualified()) | |||
7080 | AllFieldsAreConst = false; | |||
7081 | } else if (CSM == Sema::CXXCopyConstructor) { | |||
7082 | // For a copy constructor, data members must not be of rvalue reference | |||
7083 | // type. | |||
7084 | if (FieldType->isRValueReferenceType()) { | |||
7085 | if (Diagnose) | |||
7086 | S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) | |||
7087 | << MD->getParent() << FD << FieldType; | |||
7088 | return true; | |||
7089 | } | |||
7090 | } else if (IsAssignment) { | |||
7091 | // For an assignment operator, data members must not be of reference type. | |||
7092 | if (FieldType->isReferenceType()) { | |||
7093 | if (Diagnose) | |||
7094 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | |||
7095 | << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; | |||
7096 | return true; | |||
7097 | } | |||
7098 | if (!FieldRecord && FieldType.isConstQualified()) { | |||
7099 | // C++11 [class.copy]p23: | |||
7100 | // -- a non-static data member of const non-class type (or array thereof) | |||
7101 | if (Diagnose) | |||
7102 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | |||
7103 | << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; | |||
7104 | return true; | |||
7105 | } | |||
7106 | } | |||
7107 | ||||
7108 | if (FieldRecord) { | |||
7109 | // Some additional restrictions exist on the variant members. | |||
7110 | if (!inUnion() && FieldRecord->isUnion() && | |||
7111 | FieldRecord->isAnonymousStructOrUnion()) { | |||
7112 | bool AllVariantFieldsAreConst = true; | |||
7113 | ||||
7114 | // FIXME: Handle anonymous unions declared within anonymous unions. | |||
7115 | for (auto *UI : FieldRecord->fields()) { | |||
7116 | QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); | |||
7117 | ||||
7118 | if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) | |||
7119 | return true; | |||
7120 | ||||
7121 | if (!UnionFieldType.isConstQualified()) | |||
7122 | AllVariantFieldsAreConst = false; | |||
7123 | ||||
7124 | CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); | |||
7125 | if (UnionFieldRecord && | |||
7126 | shouldDeleteForClassSubobject(UnionFieldRecord, UI, | |||
7127 | UnionFieldType.getCVRQualifiers())) | |||
7128 | return true; | |||
7129 | } | |||
7130 | ||||
7131 | // At least one member in each anonymous union must be non-const | |||
7132 | if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && | |||
7133 | !FieldRecord->field_empty()) { | |||
7134 | if (Diagnose) | |||
7135 | S.Diag(FieldRecord->getLocation(), | |||
7136 | diag::note_deleted_default_ctor_all_const) | |||
7137 | << !!ICI << MD->getParent() << /*anonymous union*/1; | |||
7138 | return true; | |||
7139 | } | |||
7140 | ||||
7141 | // Don't check the implicit member of the anonymous union type. | |||
7142 | // This is technically non-conformant, but sanity demands it. | |||
7143 | return false; | |||
7144 | } | |||
7145 | ||||
7146 | if (shouldDeleteForClassSubobject(FieldRecord, FD, | |||
7147 | FieldType.getCVRQualifiers())) | |||
7148 | return true; | |||
7149 | } | |||
7150 | ||||
7151 | return false; | |||
7152 | } | |||
7153 | ||||
7154 | /// C++11 [class.ctor] p5: | |||
7155 | /// A defaulted default constructor for a class X is defined as deleted if | |||
7156 | /// X is a union and all of its variant members are of const-qualified type. | |||
7157 | bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { | |||
7158 | // This is a silly definition, because it gives an empty union a deleted | |||
7159 | // default constructor. Don't do that. | |||
7160 | if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { | |||
7161 | bool AnyFields = false; | |||
7162 | for (auto *F : MD->getParent()->fields()) | |||
7163 | if ((AnyFields = !F->isUnnamedBitfield())) | |||
7164 | break; | |||
7165 | if (!AnyFields) | |||
7166 | return false; | |||
7167 | if (Diagnose) | |||
7168 | S.Diag(MD->getParent()->getLocation(), | |||
7169 | diag::note_deleted_default_ctor_all_const) | |||
7170 | << !!ICI << MD->getParent() << /*not anonymous union*/0; | |||
7171 | return true; | |||
7172 | } | |||
7173 | return false; | |||
7174 | } | |||
7175 | ||||
7176 | /// Determine whether a defaulted special member function should be defined as | |||
7177 | /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, | |||
7178 | /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. | |||
7179 | bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
7180 | InheritedConstructorInfo *ICI, | |||
7181 | bool Diagnose) { | |||
7182 | if (MD->isInvalidDecl()) | |||
7183 | return false; | |||
7184 | CXXRecordDecl *RD = MD->getParent(); | |||
7185 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7185, __PRETTY_FUNCTION__)); | |||
7186 | if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) | |||
7187 | return false; | |||
7188 | ||||
7189 | // C++11 [expr.lambda.prim]p19: | |||
7190 | // The closure type associated with a lambda-expression has a | |||
7191 | // deleted (8.4.3) default constructor and a deleted copy | |||
7192 | // assignment operator. | |||
7193 | // C++2a adds back these operators if the lambda has no capture-default. | |||
7194 | if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && | |||
7195 | (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { | |||
7196 | if (Diagnose) | |||
7197 | Diag(RD->getLocation(), diag::note_lambda_decl); | |||
7198 | return true; | |||
7199 | } | |||
7200 | ||||
7201 | // For an anonymous struct or union, the copy and assignment special members | |||
7202 | // will never be used, so skip the check. For an anonymous union declared at | |||
7203 | // namespace scope, the constructor and destructor are used. | |||
7204 | if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && | |||
7205 | RD->isAnonymousStructOrUnion()) | |||
7206 | return false; | |||
7207 | ||||
7208 | // C++11 [class.copy]p7, p18: | |||
7209 | // If the class definition declares a move constructor or move assignment | |||
7210 | // operator, an implicitly declared copy constructor or copy assignment | |||
7211 | // operator is defined as deleted. | |||
7212 | if (MD->isImplicit() && | |||
7213 | (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { | |||
7214 | CXXMethodDecl *UserDeclaredMove = nullptr; | |||
7215 | ||||
7216 | // In Microsoft mode up to MSVC 2013, a user-declared move only causes the | |||
7217 | // deletion of the corresponding copy operation, not both copy operations. | |||
7218 | // MSVC 2015 has adopted the standards conforming behavior. | |||
7219 | bool DeletesOnlyMatchingCopy = | |||
7220 | getLangOpts().MSVCCompat && | |||
7221 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); | |||
7222 | ||||
7223 | if (RD->hasUserDeclaredMoveConstructor() && | |||
7224 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { | |||
7225 | if (!Diagnose) return true; | |||
7226 | ||||
7227 | // Find any user-declared move constructor. | |||
7228 | for (auto *I : RD->ctors()) { | |||
7229 | if (I->isMoveConstructor()) { | |||
7230 | UserDeclaredMove = I; | |||
7231 | break; | |||
7232 | } | |||
7233 | } | |||
7234 | assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7234, __PRETTY_FUNCTION__)); | |||
7235 | } else if (RD->hasUserDeclaredMoveAssignment() && | |||
7236 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { | |||
7237 | if (!Diagnose) return true; | |||
7238 | ||||
7239 | // Find any user-declared move assignment operator. | |||
7240 | for (auto *I : RD->methods()) { | |||
7241 | if (I->isMoveAssignmentOperator()) { | |||
7242 | UserDeclaredMove = I; | |||
7243 | break; | |||
7244 | } | |||
7245 | } | |||
7246 | assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7246, __PRETTY_FUNCTION__)); | |||
7247 | } | |||
7248 | ||||
7249 | if (UserDeclaredMove) { | |||
7250 | Diag(UserDeclaredMove->getLocation(), | |||
7251 | diag::note_deleted_copy_user_declared_move) | |||
7252 | << (CSM == CXXCopyAssignment) << RD | |||
7253 | << UserDeclaredMove->isMoveAssignmentOperator(); | |||
7254 | return true; | |||
7255 | } | |||
7256 | } | |||
7257 | ||||
7258 | // Do access control from the special member function | |||
7259 | ContextRAII MethodContext(*this, MD); | |||
7260 | ||||
7261 | // C++11 [class.dtor]p5: | |||
7262 | // -- for a virtual destructor, lookup of the non-array deallocation function | |||
7263 | // results in an ambiguity or in a function that is deleted or inaccessible | |||
7264 | if (CSM == CXXDestructor && MD->isVirtual()) { | |||
7265 | FunctionDecl *OperatorDelete = nullptr; | |||
7266 | DeclarationName Name = | |||
7267 | Context.DeclarationNames.getCXXOperatorName(OO_Delete); | |||
7268 | if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, | |||
7269 | OperatorDelete, /*Diagnose*/false)) { | |||
7270 | if (Diagnose) | |||
7271 | Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); | |||
7272 | return true; | |||
7273 | } | |||
7274 | } | |||
7275 | ||||
7276 | SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); | |||
7277 | ||||
7278 | // Per DR1611, do not consider virtual bases of constructors of abstract | |||
7279 | // classes, since we are not going to construct them. | |||
7280 | // Per DR1658, do not consider virtual bases of destructors of abstract | |||
7281 | // classes either. | |||
7282 | // Per DR2180, for assignment operators we only assign (and thus only | |||
7283 | // consider) direct bases. | |||
7284 | if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases | |||
7285 | : SMI.VisitPotentiallyConstructedBases)) | |||
7286 | return true; | |||
7287 | ||||
7288 | if (SMI.shouldDeleteForAllConstMembers()) | |||
7289 | return true; | |||
7290 | ||||
7291 | if (getLangOpts().CUDA) { | |||
7292 | // We should delete the special member in CUDA mode if target inference | |||
7293 | // failed. | |||
7294 | // For inherited constructors (non-null ICI), CSM may be passed so that MD | |||
7295 | // is treated as certain special member, which may not reflect what special | |||
7296 | // member MD really is. However inferCUDATargetForImplicitSpecialMember | |||
7297 | // expects CSM to match MD, therefore recalculate CSM. | |||
7298 | assert(ICI || CSM == getSpecialMember(MD))((ICI || CSM == getSpecialMember(MD)) ? static_cast<void> (0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7298, __PRETTY_FUNCTION__)); | |||
7299 | auto RealCSM = CSM; | |||
7300 | if (ICI) | |||
7301 | RealCSM = getSpecialMember(MD); | |||
7302 | ||||
7303 | return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, | |||
7304 | SMI.ConstArg, Diagnose); | |||
7305 | } | |||
7306 | ||||
7307 | return false; | |||
7308 | } | |||
7309 | ||||
7310 | /// Perform lookup for a special member of the specified kind, and determine | |||
7311 | /// whether it is trivial. If the triviality can be determined without the | |||
7312 | /// lookup, skip it. This is intended for use when determining whether a | |||
7313 | /// special member of a containing object is trivial, and thus does not ever | |||
7314 | /// perform overload resolution for default constructors. | |||
7315 | /// | |||
7316 | /// If \p Selected is not \c NULL, \c *Selected will be filled in with the | |||
7317 | /// member that was most likely to be intended to be trivial, if any. | |||
7318 | /// | |||
7319 | /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to | |||
7320 | /// determine whether the special member is trivial. | |||
7321 | static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, | |||
7322 | Sema::CXXSpecialMember CSM, unsigned Quals, | |||
7323 | bool ConstRHS, | |||
7324 | Sema::TrivialABIHandling TAH, | |||
7325 | CXXMethodDecl **Selected) { | |||
7326 | if (Selected) | |||
7327 | *Selected = nullptr; | |||
7328 | ||||
7329 | switch (CSM) { | |||
7330 | case Sema::CXXInvalid: | |||
7331 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7331); | |||
7332 | ||||
7333 | case Sema::CXXDefaultConstructor: | |||
7334 | // C++11 [class.ctor]p5: | |||
7335 | // A default constructor is trivial if: | |||
7336 | // - all the [direct subobjects] have trivial default constructors | |||
7337 | // | |||
7338 | // Note, no overload resolution is performed in this case. | |||
7339 | if (RD->hasTrivialDefaultConstructor()) | |||
7340 | return true; | |||
7341 | ||||
7342 | if (Selected) { | |||
7343 | // If there's a default constructor which could have been trivial, dig it | |||
7344 | // out. Otherwise, if there's any user-provided default constructor, point | |||
7345 | // to that as an example of why there's not a trivial one. | |||
7346 | CXXConstructorDecl *DefCtor = nullptr; | |||
7347 | if (RD->needsImplicitDefaultConstructor()) | |||
7348 | S.DeclareImplicitDefaultConstructor(RD); | |||
7349 | for (auto *CI : RD->ctors()) { | |||
7350 | if (!CI->isDefaultConstructor()) | |||
7351 | continue; | |||
7352 | DefCtor = CI; | |||
7353 | if (!DefCtor->isUserProvided()) | |||
7354 | break; | |||
7355 | } | |||
7356 | ||||
7357 | *Selected = DefCtor; | |||
7358 | } | |||
7359 | ||||
7360 | return false; | |||
7361 | ||||
7362 | case Sema::CXXDestructor: | |||
7363 | // C++11 [class.dtor]p5: | |||
7364 | // A destructor is trivial if: | |||
7365 | // - all the direct [subobjects] have trivial destructors | |||
7366 | if (RD->hasTrivialDestructor() || | |||
7367 | (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7368 | RD->hasTrivialDestructorForCall())) | |||
7369 | return true; | |||
7370 | ||||
7371 | if (Selected) { | |||
7372 | if (RD->needsImplicitDestructor()) | |||
7373 | S.DeclareImplicitDestructor(RD); | |||
7374 | *Selected = RD->getDestructor(); | |||
7375 | } | |||
7376 | ||||
7377 | return false; | |||
7378 | ||||
7379 | case Sema::CXXCopyConstructor: | |||
7380 | // C++11 [class.copy]p12: | |||
7381 | // A copy constructor is trivial if: | |||
7382 | // - the constructor selected to copy each direct [subobject] is trivial | |||
7383 | if (RD->hasTrivialCopyConstructor() || | |||
7384 | (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7385 | RD->hasTrivialCopyConstructorForCall())) { | |||
7386 | if (Quals == Qualifiers::Const) | |||
7387 | // We must either select the trivial copy constructor or reach an | |||
7388 | // ambiguity; no need to actually perform overload resolution. | |||
7389 | return true; | |||
7390 | } else if (!Selected) { | |||
7391 | return false; | |||
7392 | } | |||
7393 | // In C++98, we are not supposed to perform overload resolution here, but we | |||
7394 | // treat that as a language defect, as suggested on cxx-abi-dev, to treat | |||
7395 | // cases like B as having a non-trivial copy constructor: | |||
7396 | // struct A { template<typename T> A(T&); }; | |||
7397 | // struct B { mutable A a; }; | |||
7398 | goto NeedOverloadResolution; | |||
7399 | ||||
7400 | case Sema::CXXCopyAssignment: | |||
7401 | // C++11 [class.copy]p25: | |||
7402 | // A copy assignment operator is trivial if: | |||
7403 | // - the assignment operator selected to copy each direct [subobject] is | |||
7404 | // trivial | |||
7405 | if (RD->hasTrivialCopyAssignment()) { | |||
7406 | if (Quals == Qualifiers::Const) | |||
7407 | return true; | |||
7408 | } else if (!Selected) { | |||
7409 | return false; | |||
7410 | } | |||
7411 | // In C++98, we are not supposed to perform overload resolution here, but we | |||
7412 | // treat that as a language defect. | |||
7413 | goto NeedOverloadResolution; | |||
7414 | ||||
7415 | case Sema::CXXMoveConstructor: | |||
7416 | case Sema::CXXMoveAssignment: | |||
7417 | NeedOverloadResolution: | |||
7418 | Sema::SpecialMemberOverloadResult SMOR = | |||
7419 | lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); | |||
7420 | ||||
7421 | // The standard doesn't describe how to behave if the lookup is ambiguous. | |||
7422 | // We treat it as not making the member non-trivial, just like the standard | |||
7423 | // mandates for the default constructor. This should rarely matter, because | |||
7424 | // the member will also be deleted. | |||
7425 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | |||
7426 | return true; | |||
7427 | ||||
7428 | if (!SMOR.getMethod()) { | |||
7429 | assert(SMOR.getKind() ==((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted ) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7430, __PRETTY_FUNCTION__)) | |||
7430 | Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted ) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7430, __PRETTY_FUNCTION__)); | |||
7431 | return false; | |||
7432 | } | |||
7433 | ||||
7434 | // We deliberately don't check if we found a deleted special member. We're | |||
7435 | // not supposed to! | |||
7436 | if (Selected) | |||
7437 | *Selected = SMOR.getMethod(); | |||
7438 | ||||
7439 | if (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7440 | (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) | |||
7441 | return SMOR.getMethod()->isTrivialForCall(); | |||
7442 | return SMOR.getMethod()->isTrivial(); | |||
7443 | } | |||
7444 | ||||
7445 | llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7445); | |||
7446 | } | |||
7447 | ||||
7448 | static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { | |||
7449 | for (auto *CI : RD->ctors()) | |||
7450 | if (!CI->isImplicit()) | |||
7451 | return CI; | |||
7452 | ||||
7453 | // Look for constructor templates. | |||
7454 | typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; | |||
7455 | for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { | |||
7456 | if (CXXConstructorDecl *CD = | |||
7457 | dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) | |||
7458 | return CD; | |||
7459 | } | |||
7460 | ||||
7461 | return nullptr; | |||
7462 | } | |||
7463 | ||||
7464 | /// The kind of subobject we are checking for triviality. The values of this | |||
7465 | /// enumeration are used in diagnostics. | |||
7466 | enum TrivialSubobjectKind { | |||
7467 | /// The subobject is a base class. | |||
7468 | TSK_BaseClass, | |||
7469 | /// The subobject is a non-static data member. | |||
7470 | TSK_Field, | |||
7471 | /// The object is actually the complete object. | |||
7472 | TSK_CompleteObject | |||
7473 | }; | |||
7474 | ||||
7475 | /// Check whether the special member selected for a given type would be trivial. | |||
7476 | static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, | |||
7477 | QualType SubType, bool ConstRHS, | |||
7478 | Sema::CXXSpecialMember CSM, | |||
7479 | TrivialSubobjectKind Kind, | |||
7480 | Sema::TrivialABIHandling TAH, bool Diagnose) { | |||
7481 | CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); | |||
7482 | if (!SubRD) | |||
7483 | return true; | |||
7484 | ||||
7485 | CXXMethodDecl *Selected; | |||
7486 | if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), | |||
7487 | ConstRHS, TAH, Diagnose ? &Selected : nullptr)) | |||
7488 | return true; | |||
7489 | ||||
7490 | if (Diagnose) { | |||
7491 | if (ConstRHS) | |||
7492 | SubType.addConst(); | |||
7493 | ||||
7494 | if (!Selected && CSM == Sema::CXXDefaultConstructor) { | |||
7495 | S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) | |||
7496 | << Kind << SubType.getUnqualifiedType(); | |||
7497 | if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) | |||
7498 | S.Diag(CD->getLocation(), diag::note_user_declared_ctor); | |||
7499 | } else if (!Selected) | |||
7500 | S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) | |||
7501 | << Kind << SubType.getUnqualifiedType() << CSM << SubType; | |||
7502 | else if (Selected->isUserProvided()) { | |||
7503 | if (Kind == TSK_CompleteObject) | |||
7504 | S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) | |||
7505 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7506 | else { | |||
7507 | S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) | |||
7508 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7509 | S.Diag(Selected->getLocation(), diag::note_declared_at); | |||
7510 | } | |||
7511 | } else { | |||
7512 | if (Kind != TSK_CompleteObject) | |||
7513 | S.Diag(SubobjLoc, diag::note_nontrivial_subobject) | |||
7514 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7515 | ||||
7516 | // Explain why the defaulted or deleted special member isn't trivial. | |||
7517 | S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, | |||
7518 | Diagnose); | |||
7519 | } | |||
7520 | } | |||
7521 | ||||
7522 | return false; | |||
7523 | } | |||
7524 | ||||
7525 | /// Check whether the members of a class type allow a special member to be | |||
7526 | /// trivial. | |||
7527 | static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, | |||
7528 | Sema::CXXSpecialMember CSM, | |||
7529 | bool ConstArg, | |||
7530 | Sema::TrivialABIHandling TAH, | |||
7531 | bool Diagnose) { | |||
7532 | for (const auto *FI : RD->fields()) { | |||
7533 | if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) | |||
7534 | continue; | |||
7535 | ||||
7536 | QualType FieldType = S.Context.getBaseElementType(FI->getType()); | |||
7537 | ||||
7538 | // Pretend anonymous struct or union members are members of this class. | |||
7539 | if (FI->isAnonymousStructOrUnion()) { | |||
7540 | if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), | |||
7541 | CSM, ConstArg, TAH, Diagnose)) | |||
7542 | return false; | |||
7543 | continue; | |||
7544 | } | |||
7545 | ||||
7546 | // C++11 [class.ctor]p5: | |||
7547 | // A default constructor is trivial if [...] | |||
7548 | // -- no non-static data member of its class has a | |||
7549 | // brace-or-equal-initializer | |||
7550 | if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { | |||
7551 | if (Diagnose) | |||
7552 | S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; | |||
7553 | return false; | |||
7554 | } | |||
7555 | ||||
7556 | // Objective C ARC 4.3.5: | |||
7557 | // [...] nontrivally ownership-qualified types are [...] not trivially | |||
7558 | // default constructible, copy constructible, move constructible, copy | |||
7559 | // assignable, move assignable, or destructible [...] | |||
7560 | if (FieldType.hasNonTrivialObjCLifetime()) { | |||
7561 | if (Diagnose) | |||
7562 | S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) | |||
7563 | << RD << FieldType.getObjCLifetime(); | |||
7564 | return false; | |||
7565 | } | |||
7566 | ||||
7567 | bool ConstRHS = ConstArg && !FI->isMutable(); | |||
7568 | if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, | |||
7569 | CSM, TSK_Field, TAH, Diagnose)) | |||
7570 | return false; | |||
7571 | } | |||
7572 | ||||
7573 | return true; | |||
7574 | } | |||
7575 | ||||
7576 | /// Diagnose why the specified class does not have a trivial special member of | |||
7577 | /// the given kind. | |||
7578 | void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { | |||
7579 | QualType Ty = Context.getRecordType(RD); | |||
7580 | ||||
7581 | bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); | |||
7582 | checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, | |||
7583 | TSK_CompleteObject, TAH_IgnoreTrivialABI, | |||
7584 | /*Diagnose*/true); | |||
7585 | } | |||
7586 | ||||
7587 | /// Determine whether a defaulted or deleted special member function is trivial, | |||
7588 | /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, | |||
7589 | /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. | |||
7590 | bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
7591 | TrivialABIHandling TAH, bool Diagnose) { | |||
7592 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7592, __PRETTY_FUNCTION__)); | |||
7593 | ||||
7594 | CXXRecordDecl *RD = MD->getParent(); | |||
7595 | ||||
7596 | bool ConstArg = false; | |||
7597 | ||||
7598 | // C++11 [class.copy]p12, p25: [DR1593] | |||
7599 | // A [special member] is trivial if [...] its parameter-type-list is | |||
7600 | // equivalent to the parameter-type-list of an implicit declaration [...] | |||
7601 | switch (CSM) { | |||
7602 | case CXXDefaultConstructor: | |||
7603 | case CXXDestructor: | |||
7604 | // Trivial default constructors and destructors cannot have parameters. | |||
7605 | break; | |||
7606 | ||||
7607 | case CXXCopyConstructor: | |||
7608 | case CXXCopyAssignment: { | |||
7609 | // Trivial copy operations always have const, non-volatile parameter types. | |||
7610 | ConstArg = true; | |||
7611 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | |||
7612 | const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); | |||
7613 | if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { | |||
7614 | if (Diagnose) | |||
7615 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | |||
7616 | << Param0->getSourceRange() << Param0->getType() | |||
7617 | << Context.getLValueReferenceType( | |||
7618 | Context.getRecordType(RD).withConst()); | |||
7619 | return false; | |||
7620 | } | |||
7621 | break; | |||
7622 | } | |||
7623 | ||||
7624 | case CXXMoveConstructor: | |||
7625 | case CXXMoveAssignment: { | |||
7626 | // Trivial move operations always have non-cv-qualified parameters. | |||
7627 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | |||
7628 | const RValueReferenceType *RT = | |||
7629 | Param0->getType()->getAs<RValueReferenceType>(); | |||
7630 | if (!RT || RT->getPointeeType().getCVRQualifiers()) { | |||
7631 | if (Diagnose) | |||
7632 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | |||
7633 | << Param0->getSourceRange() << Param0->getType() | |||
7634 | << Context.getRValueReferenceType(Context.getRecordType(RD)); | |||
7635 | return false; | |||
7636 | } | |||
7637 | break; | |||
7638 | } | |||
7639 | ||||
7640 | case CXXInvalid: | |||
7641 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7641); | |||
7642 | } | |||
7643 | ||||
7644 | if (MD->getMinRequiredArguments() < MD->getNumParams()) { | |||
7645 | if (Diagnose) | |||
7646 | Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), | |||
7647 | diag::note_nontrivial_default_arg) | |||
7648 | << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); | |||
7649 | return false; | |||
7650 | } | |||
7651 | if (MD->isVariadic()) { | |||
7652 | if (Diagnose) | |||
7653 | Diag(MD->getLocation(), diag::note_nontrivial_variadic); | |||
7654 | return false; | |||
7655 | } | |||
7656 | ||||
7657 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | |||
7658 | // A copy/move [constructor or assignment operator] is trivial if | |||
7659 | // -- the [member] selected to copy/move each direct base class subobject | |||
7660 | // is trivial | |||
7661 | // | |||
7662 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7663 | // A [default constructor or destructor] is trivial if | |||
7664 | // -- all the direct base classes have trivial [default constructors or | |||
7665 | // destructors] | |||
7666 | for (const auto &BI : RD->bases()) | |||
7667 | if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), | |||
7668 | ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) | |||
7669 | return false; | |||
7670 | ||||
7671 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | |||
7672 | // A copy/move [constructor or assignment operator] for a class X is | |||
7673 | // trivial if | |||
7674 | // -- for each non-static data member of X that is of class type (or array | |||
7675 | // thereof), the constructor selected to copy/move that member is | |||
7676 | // trivial | |||
7677 | // | |||
7678 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7679 | // A [default constructor or destructor] is trivial if | |||
7680 | // -- for all of the non-static data members of its class that are of class | |||
7681 | // type (or array thereof), each such class has a trivial [default | |||
7682 | // constructor or destructor] | |||
7683 | if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) | |||
7684 | return false; | |||
7685 | ||||
7686 | // C++11 [class.dtor]p5: | |||
7687 | // A destructor is trivial if [...] | |||
7688 | // -- the destructor is not virtual | |||
7689 | if (CSM == CXXDestructor && MD->isVirtual()) { | |||
7690 | if (Diagnose) | |||
7691 | Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; | |||
7692 | return false; | |||
7693 | } | |||
7694 | ||||
7695 | // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7696 | // A [special member] for class X is trivial if [...] | |||
7697 | // -- class X has no virtual functions and no virtual base classes | |||
7698 | if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { | |||
7699 | if (!Diagnose) | |||
7700 | return false; | |||
7701 | ||||
7702 | if (RD->getNumVBases()) { | |||
7703 | // Check for virtual bases. We already know that the corresponding | |||
7704 | // member in all bases is trivial, so vbases must all be direct. | |||
7705 | CXXBaseSpecifier &BS = *RD->vbases_begin(); | |||
7706 | assert(BS.isVirtual())((BS.isVirtual()) ? static_cast<void> (0) : __assert_fail ("BS.isVirtual()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7706, __PRETTY_FUNCTION__)); | |||
7707 | Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; | |||
7708 | return false; | |||
7709 | } | |||
7710 | ||||
7711 | // Must have a virtual method. | |||
7712 | for (const auto *MI : RD->methods()) { | |||
7713 | if (MI->isVirtual()) { | |||
7714 | SourceLocation MLoc = MI->getBeginLoc(); | |||
7715 | Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; | |||
7716 | return false; | |||
7717 | } | |||
7718 | } | |||
7719 | ||||
7720 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7720); | |||
7721 | } | |||
7722 | ||||
7723 | // Looks like it's trivial! | |||
7724 | return true; | |||
7725 | } | |||
7726 | ||||
7727 | namespace { | |||
7728 | struct FindHiddenVirtualMethod { | |||
7729 | Sema *S; | |||
7730 | CXXMethodDecl *Method; | |||
7731 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; | |||
7732 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
7733 | ||||
7734 | private: | |||
7735 | /// Check whether any most overridden method from MD in Methods | |||
7736 | static bool CheckMostOverridenMethods( | |||
7737 | const CXXMethodDecl *MD, | |||
7738 | const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { | |||
7739 | if (MD->size_overridden_methods() == 0) | |||
7740 | return Methods.count(MD->getCanonicalDecl()); | |||
7741 | for (const CXXMethodDecl *O : MD->overridden_methods()) | |||
7742 | if (CheckMostOverridenMethods(O, Methods)) | |||
7743 | return true; | |||
7744 | return false; | |||
7745 | } | |||
7746 | ||||
7747 | public: | |||
7748 | /// Member lookup function that determines whether a given C++ | |||
7749 | /// method overloads virtual methods in a base class without overriding any, | |||
7750 | /// to be used with CXXRecordDecl::lookupInBases(). | |||
7751 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | |||
7752 | RecordDecl *BaseRecord = | |||
7753 | Specifier->getType()->getAs<RecordType>()->getDecl(); | |||
7754 | ||||
7755 | DeclarationName Name = Method->getDeclName(); | |||
7756 | assert(Name.getNameKind() == DeclarationName::Identifier)((Name.getNameKind() == DeclarationName::Identifier) ? static_cast <void> (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7756, __PRETTY_FUNCTION__)); | |||
7757 | ||||
7758 | bool foundSameNameMethod = false; | |||
7759 | SmallVector<CXXMethodDecl *, 8> overloadedMethods; | |||
7760 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | |||
7761 | Path.Decls = Path.Decls.slice(1)) { | |||
7762 | NamedDecl *D = Path.Decls.front(); | |||
7763 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
7764 | MD = MD->getCanonicalDecl(); | |||
7765 | foundSameNameMethod = true; | |||
7766 | // Interested only in hidden virtual methods. | |||
7767 | if (!MD->isVirtual()) | |||
7768 | continue; | |||
7769 | // If the method we are checking overrides a method from its base | |||
7770 | // don't warn about the other overloaded methods. Clang deviates from | |||
7771 | // GCC by only diagnosing overloads of inherited virtual functions that | |||
7772 | // do not override any other virtual functions in the base. GCC's | |||
7773 | // -Woverloaded-virtual diagnoses any derived function hiding a virtual | |||
7774 | // function from a base class. These cases may be better served by a | |||
7775 | // warning (not specific to virtual functions) on call sites when the | |||
7776 | // call would select a different function from the base class, were it | |||
7777 | // visible. | |||
7778 | // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. | |||
7779 | if (!S->IsOverload(Method, MD, false)) | |||
7780 | return true; | |||
7781 | // Collect the overload only if its hidden. | |||
7782 | if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) | |||
7783 | overloadedMethods.push_back(MD); | |||
7784 | } | |||
7785 | } | |||
7786 | ||||
7787 | if (foundSameNameMethod) | |||
7788 | OverloadedMethods.append(overloadedMethods.begin(), | |||
7789 | overloadedMethods.end()); | |||
7790 | return foundSameNameMethod; | |||
7791 | } | |||
7792 | }; | |||
7793 | } // end anonymous namespace | |||
7794 | ||||
7795 | /// Add the most overriden methods from MD to Methods | |||
7796 | static void AddMostOverridenMethods(const CXXMethodDecl *MD, | |||
7797 | llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { | |||
7798 | if (MD->size_overridden_methods() == 0) | |||
7799 | Methods.insert(MD->getCanonicalDecl()); | |||
7800 | else | |||
7801 | for (const CXXMethodDecl *O : MD->overridden_methods()) | |||
7802 | AddMostOverridenMethods(O, Methods); | |||
7803 | } | |||
7804 | ||||
7805 | /// Check if a method overloads virtual methods in a base class without | |||
7806 | /// overriding any. | |||
7807 | void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, | |||
7808 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | |||
7809 | if (!MD->getDeclName().isIdentifier()) | |||
7810 | return; | |||
7811 | ||||
7812 | CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. | |||
7813 | /*bool RecordPaths=*/false, | |||
7814 | /*bool DetectVirtual=*/false); | |||
7815 | FindHiddenVirtualMethod FHVM; | |||
7816 | FHVM.Method = MD; | |||
7817 | FHVM.S = this; | |||
7818 | ||||
7819 | // Keep the base methods that were overridden or introduced in the subclass | |||
7820 | // by 'using' in a set. A base method not in this set is hidden. | |||
7821 | CXXRecordDecl *DC = MD->getParent(); | |||
7822 | DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); | |||
7823 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { | |||
7824 | NamedDecl *ND = *I; | |||
7825 | if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) | |||
7826 | ND = shad->getTargetDecl(); | |||
7827 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) | |||
7828 | AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); | |||
7829 | } | |||
7830 | ||||
7831 | if (DC->lookupInBases(FHVM, Paths)) | |||
7832 | OverloadedMethods = FHVM.OverloadedMethods; | |||
7833 | } | |||
7834 | ||||
7835 | void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, | |||
7836 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | |||
7837 | for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { | |||
7838 | CXXMethodDecl *overloadedMD = OverloadedMethods[i]; | |||
7839 | PartialDiagnostic PD = PDiag( | |||
7840 | diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; | |||
7841 | HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); | |||
7842 | Diag(overloadedMD->getLocation(), PD); | |||
7843 | } | |||
7844 | } | |||
7845 | ||||
7846 | /// Diagnose methods which overload virtual methods in a base class | |||
7847 | /// without overriding any. | |||
7848 | void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { | |||
7849 | if (MD->isInvalidDecl()) | |||
7850 | return; | |||
7851 | ||||
7852 | if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) | |||
7853 | return; | |||
7854 | ||||
7855 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
7856 | FindHiddenVirtualMethods(MD, OverloadedMethods); | |||
7857 | if (!OverloadedMethods.empty()) { | |||
7858 | Diag(MD->getLocation(), diag::warn_overloaded_virtual) | |||
7859 | << MD << (OverloadedMethods.size() > 1); | |||
7860 | ||||
7861 | NoteHiddenVirtualMethods(MD, OverloadedMethods); | |||
7862 | } | |||
7863 | } | |||
7864 | ||||
7865 | void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { | |||
7866 | auto PrintDiagAndRemoveAttr = [&]() { | |||
7867 | // No diagnostics if this is a template instantiation. | |||
7868 | if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) | |||
7869 | Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), | |||
7870 | diag::ext_cannot_use_trivial_abi) << &RD; | |||
7871 | RD.dropAttr<TrivialABIAttr>(); | |||
7872 | }; | |||
7873 | ||||
7874 | // Ill-formed if the struct has virtual functions. | |||
7875 | if (RD.isPolymorphic()) { | |||
7876 | PrintDiagAndRemoveAttr(); | |||
7877 | return; | |||
7878 | } | |||
7879 | ||||
7880 | for (const auto &B : RD.bases()) { | |||
7881 | // Ill-formed if the base class is non-trivial for the purpose of calls or a | |||
7882 | // virtual base. | |||
7883 | if ((!B.getType()->isDependentType() && | |||
7884 | !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || | |||
7885 | B.isVirtual()) { | |||
7886 | PrintDiagAndRemoveAttr(); | |||
7887 | return; | |||
7888 | } | |||
7889 | } | |||
7890 | ||||
7891 | for (const auto *FD : RD.fields()) { | |||
7892 | // Ill-formed if the field is an ObjectiveC pointer or of a type that is | |||
7893 | // non-trivial for the purpose of calls. | |||
7894 | QualType FT = FD->getType(); | |||
7895 | if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { | |||
7896 | PrintDiagAndRemoveAttr(); | |||
7897 | return; | |||
7898 | } | |||
7899 | ||||
7900 | if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) | |||
7901 | if (!RT->isDependentType() && | |||
7902 | !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { | |||
7903 | PrintDiagAndRemoveAttr(); | |||
7904 | return; | |||
7905 | } | |||
7906 | } | |||
7907 | } | |||
7908 | ||||
7909 | void Sema::ActOnFinishCXXMemberSpecification( | |||
7910 | Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, | |||
7911 | SourceLocation RBrac, const ParsedAttributesView &AttrList) { | |||
7912 | if (!TagDecl) | |||
7913 | return; | |||
7914 | ||||
7915 | AdjustDeclIfTemplate(TagDecl); | |||
7916 | ||||
7917 | for (const ParsedAttr &AL : AttrList) { | |||
7918 | if (AL.getKind() != ParsedAttr::AT_Visibility) | |||
7919 | continue; | |||
7920 | AL.setInvalid(); | |||
7921 | Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) | |||
7922 | << AL.getName(); | |||
7923 | } | |||
7924 | ||||
7925 | ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( | |||
7926 | // strict aliasing violation! | |||
7927 | reinterpret_cast<Decl**>(FieldCollector->getCurFields()), | |||
7928 | FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); | |||
7929 | ||||
7930 | CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); | |||
7931 | } | |||
7932 | ||||
7933 | /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared | |||
7934 | /// special functions, such as the default constructor, copy | |||
7935 | /// constructor, or destructor, to the given C++ class (C++ | |||
7936 | /// [special]p1). This routine can only be executed just before the | |||
7937 | /// definition of the class is complete. | |||
7938 | void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { | |||
7939 | if (ClassDecl->needsImplicitDefaultConstructor()) { | |||
7940 | ++getASTContext().NumImplicitDefaultConstructors; | |||
7941 | ||||
7942 | if (ClassDecl->hasInheritedConstructor()) | |||
7943 | DeclareImplicitDefaultConstructor(ClassDecl); | |||
7944 | } | |||
7945 | ||||
7946 | if (ClassDecl->needsImplicitCopyConstructor()) { | |||
7947 | ++getASTContext().NumImplicitCopyConstructors; | |||
7948 | ||||
7949 | // If the properties or semantics of the copy constructor couldn't be | |||
7950 | // determined while the class was being declared, force a declaration | |||
7951 | // of it now. | |||
7952 | if (ClassDecl->needsOverloadResolutionForCopyConstructor() || | |||
7953 | ClassDecl->hasInheritedConstructor()) | |||
7954 | DeclareImplicitCopyConstructor(ClassDecl); | |||
7955 | // For the MS ABI we need to know whether the copy ctor is deleted. A | |||
7956 | // prerequisite for deleting the implicit copy ctor is that the class has a | |||
7957 | // move ctor or move assignment that is either user-declared or whose | |||
7958 | // semantics are inherited from a subobject. FIXME: We should provide a more | |||
7959 | // direct way for CodeGen to ask whether the constructor was deleted. | |||
7960 | else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
7961 | (ClassDecl->hasUserDeclaredMoveConstructor() || | |||
7962 | ClassDecl->needsOverloadResolutionForMoveConstructor() || | |||
7963 | ClassDecl->hasUserDeclaredMoveAssignment() || | |||
7964 | ClassDecl->needsOverloadResolutionForMoveAssignment())) | |||
7965 | DeclareImplicitCopyConstructor(ClassDecl); | |||
7966 | } | |||
7967 | ||||
7968 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { | |||
7969 | ++getASTContext().NumImplicitMoveConstructors; | |||
7970 | ||||
7971 | if (ClassDecl->needsOverloadResolutionForMoveConstructor() || | |||
7972 | ClassDecl->hasInheritedConstructor()) | |||
7973 | DeclareImplicitMoveConstructor(ClassDecl); | |||
7974 | } | |||
7975 | ||||
7976 | if (ClassDecl->needsImplicitCopyAssignment()) { | |||
7977 | ++getASTContext().NumImplicitCopyAssignmentOperators; | |||
7978 | ||||
7979 | // If we have a dynamic class, then the copy assignment operator may be | |||
7980 | // virtual, so we have to declare it immediately. This ensures that, e.g., | |||
7981 | // it shows up in the right place in the vtable and that we diagnose | |||
7982 | // problems with the implicit exception specification. | |||
7983 | if (ClassDecl->isDynamicClass() || | |||
7984 | ClassDecl->needsOverloadResolutionForCopyAssignment() || | |||
7985 | ClassDecl->hasInheritedAssignment()) | |||
7986 | DeclareImplicitCopyAssignment(ClassDecl); | |||
7987 | } | |||
7988 | ||||
7989 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { | |||
7990 | ++getASTContext().NumImplicitMoveAssignmentOperators; | |||
7991 | ||||
7992 | // Likewise for the move assignment operator. | |||
7993 | if (ClassDecl->isDynamicClass() || | |||
7994 | ClassDecl->needsOverloadResolutionForMoveAssignment() || | |||
7995 | ClassDecl->hasInheritedAssignment()) | |||
7996 | DeclareImplicitMoveAssignment(ClassDecl); | |||
7997 | } | |||
7998 | ||||
7999 | if (ClassDecl->needsImplicitDestructor()) { | |||
8000 | ++getASTContext().NumImplicitDestructors; | |||
8001 | ||||
8002 | // If we have a dynamic class, then the destructor may be virtual, so we | |||
8003 | // have to declare the destructor immediately. This ensures that, e.g., it | |||
8004 | // shows up in the right place in the vtable and that we diagnose problems | |||
8005 | // with the implicit exception specification. | |||
8006 | if (ClassDecl->isDynamicClass() || | |||
8007 | ClassDecl->needsOverloadResolutionForDestructor()) | |||
8008 | DeclareImplicitDestructor(ClassDecl); | |||
8009 | } | |||
8010 | } | |||
8011 | ||||
8012 | unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { | |||
8013 | if (!D) | |||
8014 | return 0; | |||
8015 | ||||
8016 | // The order of template parameters is not important here. All names | |||
8017 | // get added to the same scope. | |||
8018 | SmallVector<TemplateParameterList *, 4> ParameterLists; | |||
8019 | ||||
8020 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | |||
8021 | D = TD->getTemplatedDecl(); | |||
8022 | ||||
8023 | if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) | |||
8024 | ParameterLists.push_back(PSD->getTemplateParameters()); | |||
8025 | ||||
8026 | if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { | |||
8027 | for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) | |||
8028 | ParameterLists.push_back(DD->getTemplateParameterList(i)); | |||
8029 | ||||
8030 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
8031 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) | |||
8032 | ParameterLists.push_back(FTD->getTemplateParameters()); | |||
8033 | } | |||
8034 | } | |||
8035 | ||||
8036 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) { | |||
8037 | for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) | |||
8038 | ParameterLists.push_back(TD->getTemplateParameterList(i)); | |||
8039 | ||||
8040 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { | |||
8041 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) | |||
8042 | ParameterLists.push_back(CTD->getTemplateParameters()); | |||
8043 | } | |||
8044 | } | |||
8045 | ||||
8046 | unsigned Count = 0; | |||
8047 | for (TemplateParameterList *Params : ParameterLists) { | |||
8048 | if (Params->size() > 0) | |||
8049 | // Ignore explicit specializations; they don't contribute to the template | |||
8050 | // depth. | |||
8051 | ++Count; | |||
8052 | for (NamedDecl *Param : *Params) { | |||
8053 | if (Param->getDeclName()) { | |||
8054 | S->AddDecl(Param); | |||
8055 | IdResolver.AddDecl(Param); | |||
8056 | } | |||
8057 | } | |||
8058 | } | |||
8059 | ||||
8060 | return Count; | |||
8061 | } | |||
8062 | ||||
8063 | void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | |||
8064 | if (!RecordD) return; | |||
8065 | AdjustDeclIfTemplate(RecordD); | |||
8066 | CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); | |||
8067 | PushDeclContext(S, Record); | |||
8068 | } | |||
8069 | ||||
8070 | void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | |||
8071 | if (!RecordD) return; | |||
8072 | PopDeclContext(); | |||
8073 | } | |||
8074 | ||||
8075 | /// This is used to implement the constant expression evaluation part of the | |||
8076 | /// attribute enable_if extension. There is nothing in standard C++ which would | |||
8077 | /// require reentering parameters. | |||
8078 | void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { | |||
8079 | if (!Param) | |||
8080 | return; | |||
8081 | ||||
8082 | S->AddDecl(Param); | |||
8083 | if (Param->getDeclName()) | |||
8084 | IdResolver.AddDecl(Param); | |||
8085 | } | |||
8086 | ||||
8087 | /// ActOnStartDelayedCXXMethodDeclaration - We have completed | |||
8088 | /// parsing a top-level (non-nested) C++ class, and we are now | |||
8089 | /// parsing those parts of the given Method declaration that could | |||
8090 | /// not be parsed earlier (C++ [class.mem]p2), such as default | |||
8091 | /// arguments. This action should enter the scope of the given | |||
8092 | /// Method declaration as if we had just parsed the qualified method | |||
8093 | /// name. However, it should not bring the parameters into scope; | |||
8094 | /// that will be performed by ActOnDelayedCXXMethodParameter. | |||
8095 | void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | |||
8096 | } | |||
8097 | ||||
8098 | /// ActOnDelayedCXXMethodParameter - We've already started a delayed | |||
8099 | /// C++ method declaration. We're (re-)introducing the given | |||
8100 | /// function parameter into scope for use in parsing later parts of | |||
8101 | /// the method declaration. For example, we could see an | |||
8102 | /// ActOnParamDefaultArgument event for this parameter. | |||
8103 | void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { | |||
8104 | if (!ParamD) | |||
8105 | return; | |||
8106 | ||||
8107 | ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); | |||
8108 | ||||
8109 | // If this parameter has an unparsed default argument, clear it out | |||
8110 | // to make way for the parsed default argument. | |||
8111 | if (Param->hasUnparsedDefaultArg()) | |||
8112 | Param->setDefaultArg(nullptr); | |||
8113 | ||||
8114 | S->AddDecl(Param); | |||
8115 | if (Param->getDeclName()) | |||
8116 | IdResolver.AddDecl(Param); | |||
8117 | } | |||
8118 | ||||
8119 | /// ActOnFinishDelayedCXXMethodDeclaration - We have finished | |||
8120 | /// processing the delayed method declaration for Method. The method | |||
8121 | /// declaration is now considered finished. There may be a separate | |||
8122 | /// ActOnStartOfFunctionDef action later (not necessarily | |||
8123 | /// immediately!) for this method, if it was also defined inside the | |||
8124 | /// class body. | |||
8125 | void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | |||
8126 | if (!MethodD) | |||
8127 | return; | |||
8128 | ||||
8129 | AdjustDeclIfTemplate(MethodD); | |||
8130 | ||||
8131 | FunctionDecl *Method = cast<FunctionDecl>(MethodD); | |||
8132 | ||||
8133 | // Now that we have our default arguments, check the constructor | |||
8134 | // again. It could produce additional diagnostics or affect whether | |||
8135 | // the class has implicitly-declared destructors, among other | |||
8136 | // things. | |||
8137 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) | |||
8138 | CheckConstructor(Constructor); | |||
8139 | ||||
8140 | // Check the default arguments, which we may have added. | |||
8141 | if (!Method->isInvalidDecl()) | |||
8142 | CheckCXXDefaultArguments(Method); | |||
8143 | } | |||
8144 | ||||
8145 | /// CheckConstructorDeclarator - Called by ActOnDeclarator to check | |||
8146 | /// the well-formedness of the constructor declarator @p D with type @p | |||
8147 | /// R. If there are any errors in the declarator, this routine will | |||
8148 | /// emit diagnostics and set the invalid bit to true. In any case, the type | |||
8149 | /// will be updated to reflect a well-formed type for the constructor and | |||
8150 | /// returned. | |||
8151 | QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, | |||
8152 | StorageClass &SC) { | |||
8153 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | |||
8154 | ||||
8155 | // C++ [class.ctor]p3: | |||
8156 | // A constructor shall not be virtual (10.3) or static (9.4). A | |||
8157 | // constructor can be invoked for a const, volatile or const | |||
8158 | // volatile object. A constructor shall not be declared const, | |||
8159 | // volatile, or const volatile (9.3.2). | |||
8160 | if (isVirtual) { | |||
8161 | if (!D.isInvalidType()) | |||
8162 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | |||
8163 | << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) | |||
8164 | << SourceRange(D.getIdentifierLoc()); | |||
8165 | D.setInvalidType(); | |||
8166 | } | |||
8167 | if (SC == SC_Static) { | |||
8168 | if (!D.isInvalidType()) | |||
8169 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | |||
8170 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8171 | << SourceRange(D.getIdentifierLoc()); | |||
8172 | D.setInvalidType(); | |||
8173 | SC = SC_None; | |||
8174 | } | |||
8175 | ||||
8176 | if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | |||
8177 | diagnoseIgnoredQualifiers( | |||
8178 | diag::err_constructor_return_type, TypeQuals, SourceLocation(), | |||
8179 | D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), | |||
8180 | D.getDeclSpec().getRestrictSpecLoc(), | |||
8181 | D.getDeclSpec().getAtomicSpecLoc()); | |||
8182 | D.setInvalidType(); | |||
8183 | } | |||
8184 | ||||
8185 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
8186 | if (FTI.hasMethodTypeQualifiers()) { | |||
8187 | FTI.MethodQualifiers->forEachQualifier( | |||
8188 | [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { | |||
8189 | Diag(SL, diag::err_invalid_qualified_constructor) | |||
8190 | << QualName << SourceRange(SL); | |||
8191 | }); | |||
8192 | D.setInvalidType(); | |||
8193 | } | |||
8194 | ||||
8195 | // C++0x [class.ctor]p4: | |||
8196 | // A constructor shall not be declared with a ref-qualifier. | |||
8197 | if (FTI.hasRefQualifier()) { | |||
8198 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) | |||
8199 | << FTI.RefQualifierIsLValueRef | |||
8200 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | |||
8201 | D.setInvalidType(); | |||
8202 | } | |||
8203 | ||||
8204 | // Rebuild the function type "R" without any type qualifiers (in | |||
8205 | // case any of the errors above fired) and with "void" as the | |||
8206 | // return type, since constructors don't have return types. | |||
8207 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8208 | if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) | |||
8209 | return R; | |||
8210 | ||||
8211 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | |||
8212 | EPI.TypeQuals = Qualifiers(); | |||
8213 | EPI.RefQualifier = RQ_None; | |||
8214 | ||||
8215 | return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); | |||
8216 | } | |||
8217 | ||||
8218 | /// CheckConstructor - Checks a fully-formed constructor for | |||
8219 | /// well-formedness, issuing any diagnostics required. Returns true if | |||
8220 | /// the constructor declarator is invalid. | |||
8221 | void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { | |||
8222 | CXXRecordDecl *ClassDecl | |||
8223 | = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); | |||
8224 | if (!ClassDecl) | |||
8225 | return Constructor->setInvalidDecl(); | |||
8226 | ||||
8227 | // C++ [class.copy]p3: | |||
8228 | // A declaration of a constructor for a class X is ill-formed if | |||
8229 | // its first parameter is of type (optionally cv-qualified) X and | |||
8230 | // either there are no other parameters or else all other | |||
8231 | // parameters have default arguments. | |||
8232 | if (!Constructor->isInvalidDecl() && | |||
8233 | ((Constructor->getNumParams() == 1) || | |||
8234 | (Constructor->getNumParams() > 1 && | |||
8235 | Constructor->getParamDecl(1)->hasDefaultArg())) && | |||
8236 | Constructor->getTemplateSpecializationKind() | |||
8237 | != TSK_ImplicitInstantiation) { | |||
8238 | QualType ParamType = Constructor->getParamDecl(0)->getType(); | |||
8239 | QualType ClassTy = Context.getTagDeclType(ClassDecl); | |||
8240 | if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { | |||
8241 | SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); | |||
8242 | const char *ConstRef | |||
8243 | = Constructor->getParamDecl(0)->getIdentifier() ? "const &" | |||
8244 | : " const &"; | |||
8245 | Diag(ParamLoc, diag::err_constructor_byvalue_arg) | |||
8246 | << FixItHint::CreateInsertion(ParamLoc, ConstRef); | |||
8247 | ||||
8248 | // FIXME: Rather that making the constructor invalid, we should endeavor | |||
8249 | // to fix the type. | |||
8250 | Constructor->setInvalidDecl(); | |||
8251 | } | |||
8252 | } | |||
8253 | } | |||
8254 | ||||
8255 | /// CheckDestructor - Checks a fully-formed destructor definition for | |||
8256 | /// well-formedness, issuing any diagnostics required. Returns true | |||
8257 | /// on error. | |||
8258 | bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { | |||
8259 | CXXRecordDecl *RD = Destructor->getParent(); | |||
8260 | ||||
8261 | if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { | |||
8262 | SourceLocation Loc; | |||
8263 | ||||
8264 | if (!Destructor->isImplicit()) | |||
8265 | Loc = Destructor->getLocation(); | |||
8266 | else | |||
8267 | Loc = RD->getLocation(); | |||
8268 | ||||
8269 | // If we have a virtual destructor, look up the deallocation function | |||
8270 | if (FunctionDecl *OperatorDelete = | |||
8271 | FindDeallocationFunctionForDestructor(Loc, RD)) { | |||
8272 | Expr *ThisArg = nullptr; | |||
8273 | ||||
8274 | // If the notional 'delete this' expression requires a non-trivial | |||
8275 | // conversion from 'this' to the type of a destroying operator delete's | |||
8276 | // first parameter, perform that conversion now. | |||
8277 | if (OperatorDelete->isDestroyingOperatorDelete()) { | |||
8278 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); | |||
8279 | if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { | |||
8280 | // C++ [class.dtor]p13: | |||
8281 | // ... as if for the expression 'delete this' appearing in a | |||
8282 | // non-virtual destructor of the destructor's class. | |||
8283 | ContextRAII SwitchContext(*this, Destructor); | |||
8284 | ExprResult This = | |||
8285 | ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); | |||
8286 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8286, __PRETTY_FUNCTION__)); | |||
8287 | This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); | |||
8288 | if (This.isInvalid()) { | |||
8289 | // FIXME: Register this as a context note so that it comes out | |||
8290 | // in the right order. | |||
8291 | Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); | |||
8292 | return true; | |||
8293 | } | |||
8294 | ThisArg = This.get(); | |||
8295 | } | |||
8296 | } | |||
8297 | ||||
8298 | DiagnoseUseOfDecl(OperatorDelete, Loc); | |||
8299 | MarkFunctionReferenced(Loc, OperatorDelete); | |||
8300 | Destructor->setOperatorDelete(OperatorDelete, ThisArg); | |||
8301 | } | |||
8302 | } | |||
8303 | ||||
8304 | return false; | |||
8305 | } | |||
8306 | ||||
8307 | /// CheckDestructorDeclarator - Called by ActOnDeclarator to check | |||
8308 | /// the well-formednes of the destructor declarator @p D with type @p | |||
8309 | /// R. If there are any errors in the declarator, this routine will | |||
8310 | /// emit diagnostics and set the declarator to invalid. Even if this happens, | |||
8311 | /// will be updated to reflect a well-formed type for the destructor and | |||
8312 | /// returned. | |||
8313 | QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, | |||
8314 | StorageClass& SC) { | |||
8315 | // C++ [class.dtor]p1: | |||
8316 | // [...] A typedef-name that names a class is a class-name | |||
8317 | // (7.1.3); however, a typedef-name that names a class shall not | |||
8318 | // be used as the identifier in the declarator for a destructor | |||
8319 | // declaration. | |||
8320 | QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); | |||
8321 | if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) | |||
8322 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | |||
8323 | << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); | |||
8324 | else if (const TemplateSpecializationType *TST = | |||
8325 | DeclaratorType->getAs<TemplateSpecializationType>()) | |||
8326 | if (TST->isTypeAlias()) | |||
8327 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | |||
8328 | << DeclaratorType << 1; | |||
8329 | ||||
8330 | // C++ [class.dtor]p2: | |||
8331 | // A destructor is used to destroy objects of its class type. A | |||
8332 | // destructor takes no parameters, and no return type can be | |||
8333 | // specified for it (not even void). The address of a destructor | |||
8334 | // shall not be taken. A destructor shall not be static. A | |||
8335 | // destructor can be invoked for a const, volatile or const | |||
8336 | // volatile object. A destructor shall not be declared const, | |||
8337 | // volatile or const volatile (9.3.2). | |||
8338 | if (SC == SC_Static) { | |||
8339 | if (!D.isInvalidType()) | |||
8340 | Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) | |||
8341 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8342 | << SourceRange(D.getIdentifierLoc()) | |||
8343 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
8344 | ||||
8345 | SC = SC_None; | |||
8346 | } | |||
8347 | if (!D.isInvalidType()) { | |||
8348 | // Destructors don't have return types, but the parser will | |||
8349 | // happily parse something like: | |||
8350 | // | |||
8351 | // class X { | |||
8352 | // float ~X(); | |||
8353 | // }; | |||
8354 | // | |||
8355 | // The return type will be eliminated later. | |||
8356 | if (D.getDeclSpec().hasTypeSpecifier()) | |||
8357 | Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) | |||
8358 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | |||
8359 | << SourceRange(D.getIdentifierLoc()); | |||
8360 | else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | |||
8361 | diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, | |||
8362 | SourceLocation(), | |||
8363 | D.getDeclSpec().getConstSpecLoc(), | |||
8364 | D.getDeclSpec().getVolatileSpecLoc(), | |||
8365 | D.getDeclSpec().getRestrictSpecLoc(), | |||
8366 | D.getDeclSpec().getAtomicSpecLoc()); | |||
8367 | D.setInvalidType(); | |||
8368 | } | |||
8369 | } | |||
8370 | ||||
8371 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
8372 | if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { | |||
8373 | FTI.MethodQualifiers->forEachQualifier( | |||
8374 | [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) { | |||
8375 | Diag(SL, diag::err_invalid_qualified_destructor) | |||
8376 | << QualName << SourceRange(SL); | |||
8377 | }); | |||
8378 | D.setInvalidType(); | |||
8379 | } | |||
8380 | ||||
8381 | // C++0x [class.dtor]p2: | |||
8382 | // A destructor shall not be declared with a ref-qualifier. | |||
8383 | if (FTI.hasRefQualifier()) { | |||
8384 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) | |||
8385 | << FTI.RefQualifierIsLValueRef | |||
8386 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | |||
8387 | D.setInvalidType(); | |||
8388 | } | |||
8389 | ||||
8390 | // Make sure we don't have any parameters. | |||
8391 | if (FTIHasNonVoidParameters(FTI)) { | |||
8392 | Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); | |||
8393 | ||||
8394 | // Delete the parameters. | |||
8395 | FTI.freeParams(); | |||
8396 | D.setInvalidType(); | |||
8397 | } | |||
8398 | ||||
8399 | // Make sure the destructor isn't variadic. | |||
8400 | if (FTI.isVariadic) { | |||
8401 | Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); | |||
8402 | D.setInvalidType(); | |||
8403 | } | |||
8404 | ||||
8405 | // Rebuild the function type "R" without any type qualifiers or | |||
8406 | // parameters (in case any of the errors above fired) and with | |||
8407 | // "void" as the return type, since destructors don't have return | |||
8408 | // types. | |||
8409 | if (!D.isInvalidType()) | |||
8410 | return R; | |||
8411 | ||||
8412 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8413 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | |||
8414 | EPI.Variadic = false; | |||
8415 | EPI.TypeQuals = Qualifiers(); | |||
8416 | EPI.RefQualifier = RQ_None; | |||
8417 | return Context.getFunctionType(Context.VoidTy, None, EPI); | |||
8418 | } | |||
8419 | ||||
8420 | static void extendLeft(SourceRange &R, SourceRange Before) { | |||
8421 | if (Before.isInvalid()) | |||
8422 | return; | |||
8423 | R.setBegin(Before.getBegin()); | |||
8424 | if (R.getEnd().isInvalid()) | |||
8425 | R.setEnd(Before.getEnd()); | |||
8426 | } | |||
8427 | ||||
8428 | static void extendRight(SourceRange &R, SourceRange After) { | |||
8429 | if (After.isInvalid()) | |||
8430 | return; | |||
8431 | if (R.getBegin().isInvalid()) | |||
8432 | R.setBegin(After.getBegin()); | |||
8433 | R.setEnd(After.getEnd()); | |||
8434 | } | |||
8435 | ||||
8436 | /// CheckConversionDeclarator - Called by ActOnDeclarator to check the | |||
8437 | /// well-formednes of the conversion function declarator @p D with | |||
8438 | /// type @p R. If there are any errors in the declarator, this routine | |||
8439 | /// will emit diagnostics and return true. Otherwise, it will return | |||
8440 | /// false. Either way, the type @p R will be updated to reflect a | |||
8441 | /// well-formed type for the conversion operator. | |||
8442 | void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, | |||
8443 | StorageClass& SC) { | |||
8444 | // C++ [class.conv.fct]p1: | |||
8445 | // Neither parameter types nor return type can be specified. The | |||
8446 | // type of a conversion function (8.3.5) is "function taking no | |||
8447 | // parameter returning conversion-type-id." | |||
8448 | if (SC == SC_Static) { | |||
8449 | if (!D.isInvalidType()) | |||
8450 | Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) | |||
8451 | << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8452 | << D.getName().getSourceRange(); | |||
8453 | D.setInvalidType(); | |||
8454 | SC = SC_None; | |||
8455 | } | |||
8456 | ||||
8457 | TypeSourceInfo *ConvTSI = nullptr; | |||
8458 | QualType ConvType = | |||
8459 | GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); | |||
8460 | ||||
8461 | const DeclSpec &DS = D.getDeclSpec(); | |||
8462 | if (DS.hasTypeSpecifier() && !D.isInvalidType()) { | |||
8463 | // Conversion functions don't have return types, but the parser will | |||
8464 | // happily parse something like: | |||
8465 | // | |||
8466 | // class X { | |||
8467 | // float operator bool(); | |||
8468 | // }; | |||
8469 | // | |||
8470 | // The return type will be changed later anyway. | |||
8471 | Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) | |||
8472 | << SourceRange(DS.getTypeSpecTypeLoc()) | |||
8473 | << SourceRange(D.getIdentifierLoc()); | |||
8474 | D.setInvalidType(); | |||
8475 | } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { | |||
8476 | // It's also plausible that the user writes type qualifiers in the wrong | |||
8477 | // place, such as: | |||
8478 | // struct S { const operator int(); }; | |||
8479 | // FIXME: we could provide a fixit to move the qualifiers onto the | |||
8480 | // conversion type. | |||
8481 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) | |||
8482 | << SourceRange(D.getIdentifierLoc()) << 0; | |||
8483 | D.setInvalidType(); | |||
8484 | } | |||
8485 | ||||
8486 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8487 | ||||
8488 | // Make sure we don't have any parameters. | |||
8489 | if (Proto->getNumParams() > 0) { | |||
8490 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); | |||
8491 | ||||
8492 | // Delete the parameters. | |||
8493 | D.getFunctionTypeInfo().freeParams(); | |||
8494 | D.setInvalidType(); | |||
8495 | } else if (Proto->isVariadic()) { | |||
8496 | Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); | |||
8497 | D.setInvalidType(); | |||
8498 | } | |||
8499 | ||||
8500 | // Diagnose "&operator bool()" and other such nonsense. This | |||
8501 | // is actually a gcc extension which we don't support. | |||
8502 | if (Proto->getReturnType() != ConvType) { | |||
8503 | bool NeedsTypedef = false; | |||
8504 | SourceRange Before, After; | |||
8505 | ||||
8506 | // Walk the chunks and extract information on them for our diagnostic. | |||
8507 | bool PastFunctionChunk = false; | |||
8508 | for (auto &Chunk : D.type_objects()) { | |||
8509 | switch (Chunk.Kind) { | |||
8510 | case DeclaratorChunk::Function: | |||
8511 | if (!PastFunctionChunk) { | |||
8512 | if (Chunk.Fun.HasTrailingReturnType) { | |||
8513 | TypeSourceInfo *TRT = nullptr; | |||
8514 | GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); | |||
8515 | if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); | |||
8516 | } | |||
8517 | PastFunctionChunk = true; | |||
8518 | break; | |||
8519 | } | |||
8520 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
8521 | case DeclaratorChunk::Array: | |||
8522 | NeedsTypedef = true; | |||
8523 | extendRight(After, Chunk.getSourceRange()); | |||
8524 | break; | |||
8525 | ||||
8526 | case DeclaratorChunk::Pointer: | |||
8527 | case DeclaratorChunk::BlockPointer: | |||
8528 | case DeclaratorChunk::Reference: | |||
8529 | case DeclaratorChunk::MemberPointer: | |||
8530 | case DeclaratorChunk::Pipe: | |||
8531 | extendLeft(Before, Chunk.getSourceRange()); | |||
8532 | break; | |||
8533 | ||||
8534 | case DeclaratorChunk::Paren: | |||
8535 | extendLeft(Before, Chunk.Loc); | |||
8536 | extendRight(After, Chunk.EndLoc); | |||
8537 | break; | |||
8538 | } | |||
8539 | } | |||
8540 | ||||
8541 | SourceLocation Loc = Before.isValid() ? Before.getBegin() : | |||
8542 | After.isValid() ? After.getBegin() : | |||
8543 | D.getIdentifierLoc(); | |||
8544 | auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); | |||
8545 | DB << Before << After; | |||
8546 | ||||
8547 | if (!NeedsTypedef) { | |||
8548 | DB << /*don't need a typedef*/0; | |||
8549 | ||||
8550 | // If we can provide a correct fix-it hint, do so. | |||
8551 | if (After.isInvalid() && ConvTSI) { | |||
8552 | SourceLocation InsertLoc = | |||
8553 | getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); | |||
8554 | DB << FixItHint::CreateInsertion(InsertLoc, " ") | |||
8555 | << FixItHint::CreateInsertionFromRange( | |||
8556 | InsertLoc, CharSourceRange::getTokenRange(Before)) | |||
8557 | << FixItHint::CreateRemoval(Before); | |||
8558 | } | |||
8559 | } else if (!Proto->getReturnType()->isDependentType()) { | |||
8560 | DB << /*typedef*/1 << Proto->getReturnType(); | |||
8561 | } else if (getLangOpts().CPlusPlus11) { | |||
8562 | DB << /*alias template*/2 << Proto->getReturnType(); | |||
8563 | } else { | |||
8564 | DB << /*might not be fixable*/3; | |||
8565 | } | |||
8566 | ||||
8567 | // Recover by incorporating the other type chunks into the result type. | |||
8568 | // Note, this does *not* change the name of the function. This is compatible | |||
8569 | // with the GCC extension: | |||
8570 | // struct S { &operator int(); } s; | |||
8571 | // int &r = s.operator int(); // ok in GCC | |||
8572 | // S::operator int&() {} // error in GCC, function name is 'operator int'. | |||
8573 | ConvType = Proto->getReturnType(); | |||
8574 | } | |||
8575 | ||||
8576 | // C++ [class.conv.fct]p4: | |||
8577 | // The conversion-type-id shall not represent a function type nor | |||
8578 | // an array type. | |||
8579 | if (ConvType->isArrayType()) { | |||
8580 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); | |||
8581 | ConvType = Context.getPointerType(ConvType); | |||
8582 | D.setInvalidType(); | |||
8583 | } else if (ConvType->isFunctionType()) { | |||
8584 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); | |||
8585 | ConvType = Context.getPointerType(ConvType); | |||
8586 | D.setInvalidType(); | |||
8587 | } | |||
8588 | ||||
8589 | // Rebuild the function type "R" without any parameters (in case any | |||
8590 | // of the errors above fired) and with the conversion type as the | |||
8591 | // return type. | |||
8592 | if (D.isInvalidType()) | |||
8593 | R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); | |||
8594 | ||||
8595 | // C++0x explicit conversion operators. | |||
8596 | if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) | |||
8597 | Diag(DS.getExplicitSpecLoc(), | |||
8598 | getLangOpts().CPlusPlus11 | |||
8599 | ? diag::warn_cxx98_compat_explicit_conversion_functions | |||
8600 | : diag::ext_explicit_conversion_functions) | |||
8601 | << SourceRange(DS.getExplicitSpecRange()); | |||
8602 | } | |||
8603 | ||||
8604 | /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete | |||
8605 | /// the declaration of the given C++ conversion function. This routine | |||
8606 | /// is responsible for recording the conversion function in the C++ | |||
8607 | /// class, if possible. | |||
8608 | Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { | |||
8609 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8609, __PRETTY_FUNCTION__)); | |||
8610 | ||||
8611 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); | |||
8612 | ||||
8613 | // Make sure we aren't redeclaring the conversion function. | |||
8614 | QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); | |||
8615 | ||||
8616 | // C++ [class.conv.fct]p1: | |||
8617 | // [...] A conversion function is never used to convert a | |||
8618 | // (possibly cv-qualified) object to the (possibly cv-qualified) | |||
8619 | // same object type (or a reference to it), to a (possibly | |||
8620 | // cv-qualified) base class of that type (or a reference to it), | |||
8621 | // or to (possibly cv-qualified) void. | |||
8622 | // FIXME: Suppress this warning if the conversion function ends up being a | |||
8623 | // virtual function that overrides a virtual function in a base class. | |||
8624 | QualType ClassType | |||
8625 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
8626 | if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) | |||
8627 | ConvType = ConvTypeRef->getPointeeType(); | |||
8628 | if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && | |||
8629 | Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) | |||
8630 | /* Suppress diagnostics for instantiations. */; | |||
8631 | else if (ConvType->isRecordType()) { | |||
8632 | ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); | |||
8633 | if (ConvType == ClassType) | |||
8634 | Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) | |||
8635 | << ClassType; | |||
8636 | else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) | |||
8637 | Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) | |||
8638 | << ClassType << ConvType; | |||
8639 | } else if (ConvType->isVoidType()) { | |||
8640 | Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) | |||
8641 | << ClassType << ConvType; | |||
8642 | } | |||
8643 | ||||
8644 | if (FunctionTemplateDecl *ConversionTemplate | |||
8645 | = Conversion->getDescribedFunctionTemplate()) | |||
8646 | return ConversionTemplate; | |||
8647 | ||||
8648 | return Conversion; | |||
8649 | } | |||
8650 | ||||
8651 | namespace { | |||
8652 | /// Utility class to accumulate and print a diagnostic listing the invalid | |||
8653 | /// specifier(s) on a declaration. | |||
8654 | struct BadSpecifierDiagnoser { | |||
8655 | BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) | |||
8656 | : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} | |||
8657 | ~BadSpecifierDiagnoser() { | |||
8658 | Diagnostic << Specifiers; | |||
8659 | } | |||
8660 | ||||
8661 | template<typename T> void check(SourceLocation SpecLoc, T Spec) { | |||
8662 | return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); | |||
8663 | } | |||
8664 | void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { | |||
8665 | return check(SpecLoc, | |||
8666 | DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); | |||
8667 | } | |||
8668 | void check(SourceLocation SpecLoc, const char *Spec) { | |||
8669 | if (SpecLoc.isInvalid()) return; | |||
8670 | Diagnostic << SourceRange(SpecLoc, SpecLoc); | |||
8671 | if (!Specifiers.empty()) Specifiers += " "; | |||
8672 | Specifiers += Spec; | |||
8673 | } | |||
8674 | ||||
8675 | Sema &S; | |||
8676 | Sema::SemaDiagnosticBuilder Diagnostic; | |||
8677 | std::string Specifiers; | |||
8678 | }; | |||
8679 | } | |||
8680 | ||||
8681 | /// Check the validity of a declarator that we parsed for a deduction-guide. | |||
8682 | /// These aren't actually declarators in the grammar, so we need to check that | |||
8683 | /// the user didn't specify any pieces that are not part of the deduction-guide | |||
8684 | /// grammar. | |||
8685 | void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, | |||
8686 | StorageClass &SC) { | |||
8687 | TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); | |||
8688 | TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); | |||
8689 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8689, __PRETTY_FUNCTION__)); | |||
8690 | ||||
8691 | // C++ [temp.deduct.guide]p3: | |||
8692 | // A deduction-gide shall be declared in the same scope as the | |||
8693 | // corresponding class template. | |||
8694 | if (!CurContext->getRedeclContext()->Equals( | |||
8695 | GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { | |||
8696 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) | |||
8697 | << GuidedTemplateDecl; | |||
8698 | Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); | |||
8699 | } | |||
8700 | ||||
8701 | auto &DS = D.getMutableDeclSpec(); | |||
8702 | // We leave 'friend' and 'virtual' to be rejected in the normal way. | |||
8703 | if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || | |||
8704 | DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || | |||
8705 | DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { | |||
8706 | BadSpecifierDiagnoser Diagnoser( | |||
8707 | *this, D.getIdentifierLoc(), | |||
8708 | diag::err_deduction_guide_invalid_specifier); | |||
8709 | ||||
8710 | Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); | |||
8711 | DS.ClearStorageClassSpecs(); | |||
8712 | SC = SC_None; | |||
8713 | ||||
8714 | // 'explicit' is permitted. | |||
8715 | Diagnoser.check(DS.getInlineSpecLoc(), "inline"); | |||
8716 | Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); | |||
8717 | Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); | |||
8718 | DS.ClearConstexprSpec(); | |||
8719 | ||||
8720 | Diagnoser.check(DS.getConstSpecLoc(), "const"); | |||
8721 | Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); | |||
8722 | Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); | |||
8723 | Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); | |||
8724 | Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); | |||
8725 | DS.ClearTypeQualifiers(); | |||
8726 | ||||
8727 | Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); | |||
8728 | Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); | |||
8729 | Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); | |||
8730 | Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); | |||
8731 | DS.ClearTypeSpecType(); | |||
8732 | } | |||
8733 | ||||
8734 | if (D.isInvalidType()) | |||
8735 | return; | |||
8736 | ||||
8737 | // Check the declarator is simple enough. | |||
8738 | bool FoundFunction = false; | |||
8739 | for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { | |||
8740 | if (Chunk.Kind == DeclaratorChunk::Paren) | |||
8741 | continue; | |||
8742 | if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { | |||
8743 | Diag(D.getDeclSpec().getBeginLoc(), | |||
8744 | diag::err_deduction_guide_with_complex_decl) | |||
8745 | << D.getSourceRange(); | |||
8746 | break; | |||
8747 | } | |||
8748 | if (!Chunk.Fun.hasTrailingReturnType()) { | |||
8749 | Diag(D.getName().getBeginLoc(), | |||
8750 | diag::err_deduction_guide_no_trailing_return_type); | |||
8751 | break; | |||
8752 | } | |||
8753 | ||||
8754 | // Check that the return type is written as a specialization of | |||
8755 | // the template specified as the deduction-guide's name. | |||
8756 | ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); | |||
8757 | TypeSourceInfo *TSI = nullptr; | |||
8758 | QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); | |||
8759 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8759, __PRETTY_FUNCTION__)); | |||
8760 | bool AcceptableReturnType = false; | |||
8761 | bool MightInstantiateToSpecialization = false; | |||
8762 | if (auto RetTST = | |||
8763 | TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { | |||
8764 | TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); | |||
8765 | bool TemplateMatches = | |||
8766 | Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); | |||
8767 | if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) | |||
8768 | AcceptableReturnType = true; | |||
8769 | else { | |||
8770 | // This could still instantiate to the right type, unless we know it | |||
8771 | // names the wrong class template. | |||
8772 | auto *TD = SpecifiedName.getAsTemplateDecl(); | |||
8773 | MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && | |||
8774 | !TemplateMatches); | |||
8775 | } | |||
8776 | } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { | |||
8777 | MightInstantiateToSpecialization = true; | |||
8778 | } | |||
8779 | ||||
8780 | if (!AcceptableReturnType) { | |||
8781 | Diag(TSI->getTypeLoc().getBeginLoc(), | |||
8782 | diag::err_deduction_guide_bad_trailing_return_type) | |||
8783 | << GuidedTemplate << TSI->getType() | |||
8784 | << MightInstantiateToSpecialization | |||
8785 | << TSI->getTypeLoc().getSourceRange(); | |||
8786 | } | |||
8787 | ||||
8788 | // Keep going to check that we don't have any inner declarator pieces (we | |||
8789 | // could still have a function returning a pointer to a function). | |||
8790 | FoundFunction = true; | |||
8791 | } | |||
8792 | ||||
8793 | if (D.isFunctionDefinition()) | |||
8794 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); | |||
8795 | } | |||
8796 | ||||
8797 | //===----------------------------------------------------------------------===// | |||
8798 | // Namespace Handling | |||
8799 | //===----------------------------------------------------------------------===// | |||
8800 | ||||
8801 | /// Diagnose a mismatch in 'inline' qualifiers when a namespace is | |||
8802 | /// reopened. | |||
8803 | static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, | |||
8804 | SourceLocation Loc, | |||
8805 | IdentifierInfo *II, bool *IsInline, | |||
8806 | NamespaceDecl *PrevNS) { | |||
8807 | assert(*IsInline != PrevNS->isInline())((*IsInline != PrevNS->isInline()) ? static_cast<void> (0) : __assert_fail ("*IsInline != PrevNS->isInline()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8807, __PRETTY_FUNCTION__)); | |||
8808 | ||||
8809 | // HACK: Work around a bug in libstdc++4.6's <atomic>, where | |||
8810 | // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as | |||
8811 | // inline namespaces, with the intention of bringing names into namespace std. | |||
8812 | // | |||
8813 | // We support this just well enough to get that case working; this is not | |||
8814 | // sufficient to support reopening namespaces as inline in general. | |||
8815 | if (*IsInline && II && II->getName().startswith("__atomic") && | |||
8816 | S.getSourceManager().isInSystemHeader(Loc)) { | |||
8817 | // Mark all prior declarations of the namespace as inline. | |||
8818 | for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; | |||
8819 | NS = NS->getPreviousDecl()) | |||
8820 | NS->setInline(*IsInline); | |||
8821 | // Patch up the lookup table for the containing namespace. This isn't really | |||
8822 | // correct, but it's good enough for this particular case. | |||
8823 | for (auto *I : PrevNS->decls()) | |||
8824 | if (auto *ND = dyn_cast<NamedDecl>(I)) | |||
8825 | PrevNS->getParent()->makeDeclVisibleInContext(ND); | |||
8826 | return; | |||
8827 | } | |||
8828 | ||||
8829 | if (PrevNS->isInline()) | |||
8830 | // The user probably just forgot the 'inline', so suggest that it | |||
8831 | // be added back. | |||
8832 | S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) | |||
8833 | << FixItHint::CreateInsertion(KeywordLoc, "inline "); | |||
8834 | else | |||
8835 | S.Diag(Loc, diag::err_inline_namespace_mismatch); | |||
8836 | ||||
8837 | S.Diag(PrevNS->getLocation(), diag::note_previous_definition); | |||
8838 | *IsInline = PrevNS->isInline(); | |||
8839 | } | |||
8840 | ||||
8841 | /// ActOnStartNamespaceDef - This is called at the start of a namespace | |||
8842 | /// definition. | |||
8843 | Decl *Sema::ActOnStartNamespaceDef( | |||
8844 | Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, | |||
8845 | SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, | |||
8846 | const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { | |||
8847 | SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; | |||
8848 | // For anonymous namespace, take the location of the left brace. | |||
8849 | SourceLocation Loc = II ? IdentLoc : LBrace; | |||
8850 | bool IsInline = InlineLoc.isValid(); | |||
8851 | bool IsInvalid = false; | |||
8852 | bool IsStd = false; | |||
8853 | bool AddToKnown = false; | |||
8854 | Scope *DeclRegionScope = NamespcScope->getParent(); | |||
8855 | ||||
8856 | NamespaceDecl *PrevNS = nullptr; | |||
8857 | if (II) { | |||
8858 | // C++ [namespace.def]p2: | |||
8859 | // The identifier in an original-namespace-definition shall not | |||
8860 | // have been previously defined in the declarative region in | |||
8861 | // which the original-namespace-definition appears. The | |||
8862 | // identifier in an original-namespace-definition is the name of | |||
8863 | // the namespace. Subsequently in that declarative region, it is | |||
8864 | // treated as an original-namespace-name. | |||
8865 | // | |||
8866 | // Since namespace names are unique in their scope, and we don't | |||
8867 | // look through using directives, just look for any ordinary names | |||
8868 | // as if by qualified name lookup. | |||
8869 | LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, | |||
8870 | ForExternalRedeclaration); | |||
8871 | LookupQualifiedName(R, CurContext->getRedeclContext()); | |||
8872 | NamedDecl *PrevDecl = | |||
8873 | R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; | |||
8874 | PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); | |||
8875 | ||||
8876 | if (PrevNS) { | |||
8877 | // This is an extended namespace definition. | |||
8878 | if (IsInline != PrevNS->isInline()) | |||
8879 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, | |||
8880 | &IsInline, PrevNS); | |||
8881 | } else if (PrevDecl) { | |||
8882 | // This is an invalid name redefinition. | |||
8883 | Diag(Loc, diag::err_redefinition_different_kind) | |||
8884 | << II; | |||
8885 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
8886 | IsInvalid = true; | |||
8887 | // Continue on to push Namespc as current DeclContext and return it. | |||
8888 | } else if (II->isStr("std") && | |||
8889 | CurContext->getRedeclContext()->isTranslationUnit()) { | |||
8890 | // This is the first "real" definition of the namespace "std", so update | |||
8891 | // our cache of the "std" namespace to point at this definition. | |||
8892 | PrevNS = getStdNamespace(); | |||
8893 | IsStd = true; | |||
8894 | AddToKnown = !IsInline; | |||
8895 | } else { | |||
8896 | // We've seen this namespace for the first time. | |||
8897 | AddToKnown = !IsInline; | |||
8898 | } | |||
8899 | } else { | |||
8900 | // Anonymous namespaces. | |||
8901 | ||||
8902 | // Determine whether the parent already has an anonymous namespace. | |||
8903 | DeclContext *Parent = CurContext->getRedeclContext(); | |||
8904 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | |||
8905 | PrevNS = TU->getAnonymousNamespace(); | |||
8906 | } else { | |||
8907 | NamespaceDecl *ND = cast<NamespaceDecl>(Parent); | |||
8908 | PrevNS = ND->getAnonymousNamespace(); | |||
8909 | } | |||
8910 | ||||
8911 | if (PrevNS && IsInline != PrevNS->isInline()) | |||
8912 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, | |||
8913 | &IsInline, PrevNS); | |||
8914 | } | |||
8915 | ||||
8916 | NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, | |||
8917 | StartLoc, Loc, II, PrevNS); | |||
8918 | if (IsInvalid) | |||
8919 | Namespc->setInvalidDecl(); | |||
8920 | ||||
8921 | ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); | |||
8922 | AddPragmaAttributes(DeclRegionScope, Namespc); | |||
8923 | ||||
8924 | // FIXME: Should we be merging attributes? | |||
8925 | if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) | |||
8926 | PushNamespaceVisibilityAttr(Attr, Loc); | |||
8927 | ||||
8928 | if (IsStd) | |||
8929 | StdNamespace = Namespc; | |||
8930 | if (AddToKnown) | |||
8931 | KnownNamespaces[Namespc] = false; | |||
8932 | ||||
8933 | if (II) { | |||
8934 | PushOnScopeChains(Namespc, DeclRegionScope); | |||
8935 | } else { | |||
8936 | // Link the anonymous namespace into its parent. | |||
8937 | DeclContext *Parent = CurContext->getRedeclContext(); | |||
8938 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | |||
8939 | TU->setAnonymousNamespace(Namespc); | |||
8940 | } else { | |||
8941 | cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); | |||
8942 | } | |||
8943 | ||||
8944 | CurContext->addDecl(Namespc); | |||
8945 | ||||
8946 | // C++ [namespace.unnamed]p1. An unnamed-namespace-definition | |||
8947 | // behaves as if it were replaced by | |||
8948 | // namespace unique { /* empty body */ } | |||
8949 | // using namespace unique; | |||
8950 | // namespace unique { namespace-body } | |||
8951 | // where all occurrences of 'unique' in a translation unit are | |||
8952 | // replaced by the same identifier and this identifier differs | |||
8953 | // from all other identifiers in the entire program. | |||
8954 | ||||
8955 | // We just create the namespace with an empty name and then add an | |||
8956 | // implicit using declaration, just like the standard suggests. | |||
8957 | // | |||
8958 | // CodeGen enforces the "universally unique" aspect by giving all | |||
8959 | // declarations semantically contained within an anonymous | |||
8960 | // namespace internal linkage. | |||
8961 | ||||
8962 | if (!PrevNS) { | |||
8963 | UD = UsingDirectiveDecl::Create(Context, Parent, | |||
8964 | /* 'using' */ LBrace, | |||
8965 | /* 'namespace' */ SourceLocation(), | |||
8966 | /* qualifier */ NestedNameSpecifierLoc(), | |||
8967 | /* identifier */ SourceLocation(), | |||
8968 | Namespc, | |||
8969 | /* Ancestor */ Parent); | |||
8970 | UD->setImplicit(); | |||
8971 | Parent->addDecl(UD); | |||
8972 | } | |||
8973 | } | |||
8974 | ||||
8975 | ActOnDocumentableDecl(Namespc); | |||
8976 | ||||
8977 | // Although we could have an invalid decl (i.e. the namespace name is a | |||
8978 | // redefinition), push it as current DeclContext and try to continue parsing. | |||
8979 | // FIXME: We should be able to push Namespc here, so that the each DeclContext | |||
8980 | // for the namespace has the declarations that showed up in that particular | |||
8981 | // namespace definition. | |||
8982 | PushDeclContext(NamespcScope, Namespc); | |||
8983 | return Namespc; | |||
8984 | } | |||
8985 | ||||
8986 | /// getNamespaceDecl - Returns the namespace a decl represents. If the decl | |||
8987 | /// is a namespace alias, returns the namespace it points to. | |||
8988 | static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { | |||
8989 | if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) | |||
8990 | return AD->getNamespace(); | |||
8991 | return dyn_cast_or_null<NamespaceDecl>(D); | |||
8992 | } | |||
8993 | ||||
8994 | /// ActOnFinishNamespaceDef - This callback is called after a namespace is | |||
8995 | /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. | |||
8996 | void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { | |||
8997 | NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); | |||
8998 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8998, __PRETTY_FUNCTION__)); | |||
8999 | Namespc->setRBraceLoc(RBrace); | |||
9000 | PopDeclContext(); | |||
9001 | if (Namespc->hasAttr<VisibilityAttr>()) | |||
9002 | PopPragmaVisibility(true, RBrace); | |||
9003 | // If this namespace contains an export-declaration, export it now. | |||
9004 | if (DeferredExportedNamespaces.erase(Namespc)) | |||
9005 | Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); | |||
9006 | } | |||
9007 | ||||
9008 | CXXRecordDecl *Sema::getStdBadAlloc() const { | |||
9009 | return cast_or_null<CXXRecordDecl>( | |||
9010 | StdBadAlloc.get(Context.getExternalSource())); | |||
9011 | } | |||
9012 | ||||
9013 | EnumDecl *Sema::getStdAlignValT() const { | |||
9014 | return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); | |||
9015 | } | |||
9016 | ||||
9017 | NamespaceDecl *Sema::getStdNamespace() const { | |||
9018 | return cast_or_null<NamespaceDecl>( | |||
9019 | StdNamespace.get(Context.getExternalSource())); | |||
9020 | } | |||
9021 | ||||
9022 | NamespaceDecl *Sema::lookupStdExperimentalNamespace() { | |||
9023 | if (!StdExperimentalNamespaceCache) { | |||
9024 | if (auto Std = getStdNamespace()) { | |||
9025 | LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), | |||
9026 | SourceLocation(), LookupNamespaceName); | |||
9027 | if (!LookupQualifiedName(Result, Std) || | |||
9028 | !(StdExperimentalNamespaceCache = | |||
9029 | Result.getAsSingle<NamespaceDecl>())) | |||
9030 | Result.suppressDiagnostics(); | |||
9031 | } | |||
9032 | } | |||
9033 | return StdExperimentalNamespaceCache; | |||
9034 | } | |||
9035 | ||||
9036 | namespace { | |||
9037 | ||||
9038 | enum UnsupportedSTLSelect { | |||
9039 | USS_InvalidMember, | |||
9040 | USS_MissingMember, | |||
9041 | USS_NonTrivial, | |||
9042 | USS_Other | |||
9043 | }; | |||
9044 | ||||
9045 | struct InvalidSTLDiagnoser { | |||
9046 | Sema &S; | |||
9047 | SourceLocation Loc; | |||
9048 | QualType TyForDiags; | |||
9049 | ||||
9050 | QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", | |||
9051 | const VarDecl *VD = nullptr) { | |||
9052 | { | |||
9053 | auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) | |||
9054 | << TyForDiags << ((int)Sel); | |||
9055 | if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { | |||
9056 | assert(!Name.empty())((!Name.empty()) ? static_cast<void> (0) : __assert_fail ("!Name.empty()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9056, __PRETTY_FUNCTION__)); | |||
9057 | D << Name; | |||
9058 | } | |||
9059 | } | |||
9060 | if (Sel == USS_InvalidMember) { | |||
9061 | S.Diag(VD->getLocation(), diag::note_var_declared_here) | |||
9062 | << VD << VD->getSourceRange(); | |||
9063 | } | |||
9064 | return QualType(); | |||
9065 | } | |||
9066 | }; | |||
9067 | } // namespace | |||
9068 | ||||
9069 | QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, | |||
9070 | SourceLocation Loc) { | |||
9071 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9072, __PRETTY_FUNCTION__)) | |||
9072 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9072, __PRETTY_FUNCTION__)); | |||
9073 | ||||
9074 | // Check if we've already successfully checked the comparison category type | |||
9075 | // before. If so, skip checking it again. | |||
9076 | ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); | |||
9077 | if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) | |||
9078 | return Info->getType(); | |||
9079 | ||||
9080 | // If lookup failed | |||
9081 | if (!Info) { | |||
9082 | std::string NameForDiags = "std::"; | |||
9083 | NameForDiags += ComparisonCategories::getCategoryString(Kind); | |||
9084 | Diag(Loc, diag::err_implied_comparison_category_type_not_found) | |||
9085 | << NameForDiags; | |||
9086 | return QualType(); | |||
9087 | } | |||
9088 | ||||
9089 | assert(Info->Kind == Kind)((Info->Kind == Kind) ? static_cast<void> (0) : __assert_fail ("Info->Kind == Kind", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9089, __PRETTY_FUNCTION__)); | |||
9090 | assert(Info->Record)((Info->Record) ? static_cast<void> (0) : __assert_fail ("Info->Record", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9090, __PRETTY_FUNCTION__)); | |||
9091 | ||||
9092 | // Update the Record decl in case we encountered a forward declaration on our | |||
9093 | // first pass. FIXME: This is a bit of a hack. | |||
9094 | if (Info->Record->hasDefinition()) | |||
9095 | Info->Record = Info->Record->getDefinition(); | |||
9096 | ||||
9097 | // Use an elaborated type for diagnostics which has a name containing the | |||
9098 | // prepended 'std' namespace but not any inline namespace names. | |||
9099 | QualType TyForDiags = [&]() { | |||
9100 | auto *NNS = | |||
9101 | NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); | |||
9102 | return Context.getElaboratedType(ETK_None, NNS, Info->getType()); | |||
9103 | }(); | |||
9104 | ||||
9105 | if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) | |||
9106 | return QualType(); | |||
9107 | ||||
9108 | InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; | |||
9109 | ||||
9110 | if (!Info->Record->isTriviallyCopyable()) | |||
9111 | return UnsupportedSTLError(USS_NonTrivial); | |||
9112 | ||||
9113 | for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { | |||
9114 | CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); | |||
9115 | // Tolerate empty base classes. | |||
9116 | if (Base->isEmpty()) | |||
9117 | continue; | |||
9118 | // Reject STL implementations which have at least one non-empty base. | |||
9119 | return UnsupportedSTLError(); | |||
9120 | } | |||
9121 | ||||
9122 | // Check that the STL has implemented the types using a single integer field. | |||
9123 | // This expectation allows better codegen for builtin operators. We require: | |||
9124 | // (1) The class has exactly one field. | |||
9125 | // (2) The field is an integral or enumeration type. | |||
9126 | auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); | |||
9127 | if (std::distance(FIt, FEnd) != 1 || | |||
9128 | !FIt->getType()->isIntegralOrEnumerationType()) { | |||
9129 | return UnsupportedSTLError(); | |||
9130 | } | |||
9131 | ||||
9132 | // Build each of the require values and store them in Info. | |||
9133 | for (ComparisonCategoryResult CCR : | |||
9134 | ComparisonCategories::getPossibleResultsForType(Kind)) { | |||
9135 | StringRef MemName = ComparisonCategories::getResultString(CCR); | |||
9136 | ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); | |||
9137 | ||||
9138 | if (!ValInfo) | |||
9139 | return UnsupportedSTLError(USS_MissingMember, MemName); | |||
9140 | ||||
9141 | VarDecl *VD = ValInfo->VD; | |||
9142 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9142, __PRETTY_FUNCTION__)); | |||
9143 | ||||
9144 | // Attempt to diagnose reasons why the STL definition of this type | |||
9145 | // might be foobar, including it failing to be a constant expression. | |||
9146 | // TODO Handle more ways the lookup or result can be invalid. | |||
9147 | if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || | |||
9148 | !VD->checkInitIsICE()) | |||
9149 | return UnsupportedSTLError(USS_InvalidMember, MemName, VD); | |||
9150 | ||||
9151 | // Attempt to evaluate the var decl as a constant expression and extract | |||
9152 | // the value of its first field as a ICE. If this fails, the STL | |||
9153 | // implementation is not supported. | |||
9154 | if (!ValInfo->hasValidIntValue()) | |||
9155 | return UnsupportedSTLError(); | |||
9156 | ||||
9157 | MarkVariableReferenced(Loc, VD); | |||
9158 | } | |||
9159 | ||||
9160 | // We've successfully built the required types and expressions. Update | |||
9161 | // the cache and return the newly cached value. | |||
9162 | FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; | |||
9163 | return Info->getType(); | |||
9164 | } | |||
9165 | ||||
9166 | /// Retrieve the special "std" namespace, which may require us to | |||
9167 | /// implicitly define the namespace. | |||
9168 | NamespaceDecl *Sema::getOrCreateStdNamespace() { | |||
9169 | if (!StdNamespace) { | |||
9170 | // The "std" namespace has not yet been defined, so build one implicitly. | |||
9171 | StdNamespace = NamespaceDecl::Create(Context, | |||
9172 | Context.getTranslationUnitDecl(), | |||
9173 | /*Inline=*/false, | |||
9174 | SourceLocation(), SourceLocation(), | |||
9175 | &PP.getIdentifierTable().get("std"), | |||
9176 | /*PrevDecl=*/nullptr); | |||
9177 | getStdNamespace()->setImplicit(true); | |||
9178 | } | |||
9179 | ||||
9180 | return getStdNamespace(); | |||
9181 | } | |||
9182 | ||||
9183 | bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { | |||
9184 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9185, __PRETTY_FUNCTION__)) | |||
9185 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9185, __PRETTY_FUNCTION__)); | |||
9186 | ||||
9187 | // We're looking for implicit instantiations of | |||
9188 | // template <typename E> class std::initializer_list. | |||
9189 | ||||
9190 | if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. | |||
9191 | return false; | |||
9192 | ||||
9193 | ClassTemplateDecl *Template = nullptr; | |||
9194 | const TemplateArgument *Arguments = nullptr; | |||
9195 | ||||
9196 | if (const RecordType *RT = Ty->getAs<RecordType>()) { | |||
9197 | ||||
9198 | ClassTemplateSpecializationDecl *Specialization = | |||
9199 | dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); | |||
9200 | if (!Specialization) | |||
9201 | return false; | |||
9202 | ||||
9203 | Template = Specialization->getSpecializedTemplate(); | |||
9204 | Arguments = Specialization->getTemplateArgs().data(); | |||
9205 | } else if (const TemplateSpecializationType *TST = | |||
9206 | Ty->getAs<TemplateSpecializationType>()) { | |||
9207 | Template = dyn_cast_or_null<ClassTemplateDecl>( | |||
9208 | TST->getTemplateName().getAsTemplateDecl()); | |||
9209 | Arguments = TST->getArgs(); | |||
9210 | } | |||
9211 | if (!Template) | |||
9212 | return false; | |||
9213 | ||||
9214 | if (!StdInitializerList) { | |||
9215 | // Haven't recognized std::initializer_list yet, maybe this is it. | |||
9216 | CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); | |||
9217 | if (TemplateClass->getIdentifier() != | |||
9218 | &PP.getIdentifierTable().get("initializer_list") || | |||
9219 | !getStdNamespace()->InEnclosingNamespaceSetOf( | |||
9220 | TemplateClass->getDeclContext())) | |||
9221 | return false; | |||
9222 | // This is a template called std::initializer_list, but is it the right | |||
9223 | // template? | |||
9224 | TemplateParameterList *Params = Template->getTemplateParameters(); | |||
9225 | if (Params->getMinRequiredArguments() != 1) | |||
9226 | return false; | |||
9227 | if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) | |||
9228 | return false; | |||
9229 | ||||
9230 | // It's the right template. | |||
9231 | StdInitializerList = Template; | |||
9232 | } | |||
9233 | ||||
9234 | if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) | |||
9235 | return false; | |||
9236 | ||||
9237 | // This is an instance of std::initializer_list. Find the argument type. | |||
9238 | if (Element) | |||
9239 | *Element = Arguments[0].getAsType(); | |||
9240 | return true; | |||
9241 | } | |||
9242 | ||||
9243 | static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ | |||
9244 | NamespaceDecl *Std = S.getStdNamespace(); | |||
9245 | if (!Std) { | |||
9246 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | |||
9247 | return nullptr; | |||
9248 | } | |||
9249 | ||||
9250 | LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), | |||
9251 | Loc, Sema::LookupOrdinaryName); | |||
9252 | if (!S.LookupQualifiedName(Result, Std)) { | |||
9253 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | |||
9254 | return nullptr; | |||
9255 | } | |||
9256 | ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); | |||
9257 | if (!Template) { | |||
9258 | Result.suppressDiagnostics(); | |||
9259 | // We found something weird. Complain about the first thing we found. | |||
9260 | NamedDecl *Found = *Result.begin(); | |||
9261 | S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); | |||
9262 | return nullptr; | |||
9263 | } | |||
9264 | ||||
9265 | // We found some template called std::initializer_list. Now verify that it's | |||
9266 | // correct. | |||
9267 | TemplateParameterList *Params = Template->getTemplateParameters(); | |||
9268 | if (Params->getMinRequiredArguments() != 1 || | |||
9269 | !isa<TemplateTypeParmDecl>(Params->getParam(0))) { | |||
9270 | S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); | |||
9271 | return nullptr; | |||
9272 | } | |||
9273 | ||||
9274 | return Template; | |||
9275 | } | |||
9276 | ||||
9277 | QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { | |||
9278 | if (!StdInitializerList) { | |||
9279 | StdInitializerList = LookupStdInitializerList(*this, Loc); | |||
9280 | if (!StdInitializerList) | |||
9281 | return QualType(); | |||
9282 | } | |||
9283 | ||||
9284 | TemplateArgumentListInfo Args(Loc, Loc); | |||
9285 | Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), | |||
9286 | Context.getTrivialTypeSourceInfo(Element, | |||
9287 | Loc))); | |||
9288 | return Context.getCanonicalType( | |||
9289 | CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); | |||
9290 | } | |||
9291 | ||||
9292 | bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { | |||
9293 | // C++ [dcl.init.list]p2: | |||
9294 | // A constructor is an initializer-list constructor if its first parameter | |||
9295 | // is of type std::initializer_list<E> or reference to possibly cv-qualified | |||
9296 | // std::initializer_list<E> for some type E, and either there are no other | |||
9297 | // parameters or else all other parameters have default arguments. | |||
9298 | if (Ctor->getNumParams() < 1 || | |||
9299 | (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) | |||
9300 | return false; | |||
9301 | ||||
9302 | QualType ArgType = Ctor->getParamDecl(0)->getType(); | |||
9303 | if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) | |||
9304 | ArgType = RT->getPointeeType().getUnqualifiedType(); | |||
9305 | ||||
9306 | return isStdInitializerList(ArgType, nullptr); | |||
9307 | } | |||
9308 | ||||
9309 | /// Determine whether a using statement is in a context where it will be | |||
9310 | /// apply in all contexts. | |||
9311 | static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { | |||
9312 | switch (CurContext->getDeclKind()) { | |||
9313 | case Decl::TranslationUnit: | |||
9314 | return true; | |||
9315 | case Decl::LinkageSpec: | |||
9316 | return IsUsingDirectiveInToplevelContext(CurContext->getParent()); | |||
9317 | default: | |||
9318 | return false; | |||
9319 | } | |||
9320 | } | |||
9321 | ||||
9322 | namespace { | |||
9323 | ||||
9324 | // Callback to only accept typo corrections that are namespaces. | |||
9325 | class NamespaceValidatorCCC final : public CorrectionCandidateCallback { | |||
9326 | public: | |||
9327 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
9328 | if (NamedDecl *ND = candidate.getCorrectionDecl()) | |||
9329 | return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); | |||
9330 | return false; | |||
9331 | } | |||
9332 | ||||
9333 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
9334 | return llvm::make_unique<NamespaceValidatorCCC>(*this); | |||
9335 | } | |||
9336 | }; | |||
9337 | ||||
9338 | } | |||
9339 | ||||
9340 | static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, | |||
9341 | CXXScopeSpec &SS, | |||
9342 | SourceLocation IdentLoc, | |||
9343 | IdentifierInfo *Ident) { | |||
9344 | R.clear(); | |||
9345 | NamespaceValidatorCCC CCC{}; | |||
9346 | if (TypoCorrection Corrected = | |||
9347 | S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, | |||
9348 | Sema::CTK_ErrorRecovery)) { | |||
9349 | if (DeclContext *DC = S.computeDeclContext(SS, false)) { | |||
9350 | std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); | |||
9351 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
9352 | Ident->getName().equals(CorrectedStr); | |||
9353 | S.diagnoseTypo(Corrected, | |||
9354 | S.PDiag(diag::err_using_directive_member_suggest) | |||
9355 | << Ident << DC << DroppedSpecifier << SS.getRange(), | |||
9356 | S.PDiag(diag::note_namespace_defined_here)); | |||
9357 | } else { | |||
9358 | S.diagnoseTypo(Corrected, | |||
9359 | S.PDiag(diag::err_using_directive_suggest) << Ident, | |||
9360 | S.PDiag(diag::note_namespace_defined_here)); | |||
9361 | } | |||
9362 | R.addDecl(Corrected.getFoundDecl()); | |||
9363 | return true; | |||
9364 | } | |||
9365 | return false; | |||
9366 | } | |||
9367 | ||||
9368 | Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, | |||
9369 | SourceLocation NamespcLoc, CXXScopeSpec &SS, | |||
9370 | SourceLocation IdentLoc, | |||
9371 | IdentifierInfo *NamespcName, | |||
9372 | const ParsedAttributesView &AttrList) { | |||
9373 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast <void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9373, __PRETTY_FUNCTION__)); | |||
9374 | assert(NamespcName && "Invalid NamespcName.")((NamespcName && "Invalid NamespcName.") ? static_cast <void> (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9374, __PRETTY_FUNCTION__)); | |||
9375 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9375, __PRETTY_FUNCTION__)); | |||
9376 | ||||
9377 | // This can only happen along a recovery path. | |||
9378 | while (S->isTemplateParamScope()) | |||
9379 | S = S->getParent(); | |||
9380 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9380, __PRETTY_FUNCTION__)); | |||
9381 | ||||
9382 | UsingDirectiveDecl *UDir = nullptr; | |||
9383 | NestedNameSpecifier *Qualifier = nullptr; | |||
9384 | if (SS.isSet()) | |||
9385 | Qualifier = SS.getScopeRep(); | |||
9386 | ||||
9387 | // Lookup namespace name. | |||
9388 | LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); | |||
9389 | LookupParsedName(R, S, &SS); | |||
9390 | if (R.isAmbiguous()) | |||
9391 | return nullptr; | |||
9392 | ||||
9393 | if (R.empty()) { | |||
9394 | R.clear(); | |||
9395 | // Allow "using namespace std;" or "using namespace ::std;" even if | |||
9396 | // "std" hasn't been defined yet, for GCC compatibility. | |||
9397 | if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && | |||
9398 | NamespcName->isStr("std")) { | |||
9399 | Diag(IdentLoc, diag::ext_using_undefined_std); | |||
9400 | R.addDecl(getOrCreateStdNamespace()); | |||
9401 | R.resolveKind(); | |||
9402 | } | |||
9403 | // Otherwise, attempt typo correction. | |||
9404 | else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); | |||
9405 | } | |||
9406 | ||||
9407 | if (!R.empty()) { | |||
9408 | NamedDecl *Named = R.getRepresentativeDecl(); | |||
9409 | NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); | |||
9410 | assert(NS && "expected namespace decl")((NS && "expected namespace decl") ? static_cast<void > (0) : __assert_fail ("NS && \"expected namespace decl\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9410, __PRETTY_FUNCTION__)); | |||
9411 | ||||
9412 | // The use of a nested name specifier may trigger deprecation warnings. | |||
9413 | DiagnoseUseOfDecl(Named, IdentLoc); | |||
9414 | ||||
9415 | // C++ [namespace.udir]p1: | |||
9416 | // A using-directive specifies that the names in the nominated | |||
9417 | // namespace can be used in the scope in which the | |||
9418 | // using-directive appears after the using-directive. During | |||
9419 | // unqualified name lookup (3.4.1), the names appear as if they | |||
9420 | // were declared in the nearest enclosing namespace which | |||
9421 | // contains both the using-directive and the nominated | |||
9422 | // namespace. [Note: in this context, "contains" means "contains | |||
9423 | // directly or indirectly". ] | |||
9424 | ||||
9425 | // Find enclosing context containing both using-directive and | |||
9426 | // nominated namespace. | |||
9427 | DeclContext *CommonAncestor = NS; | |||
9428 | while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) | |||
9429 | CommonAncestor = CommonAncestor->getParent(); | |||
9430 | ||||
9431 | UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, | |||
9432 | SS.getWithLocInContext(Context), | |||
9433 | IdentLoc, Named, CommonAncestor); | |||
9434 | ||||
9435 | if (IsUsingDirectiveInToplevelContext(CurContext) && | |||
9436 | !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { | |||
9437 | Diag(IdentLoc, diag::warn_using_directive_in_header); | |||
9438 | } | |||
9439 | ||||
9440 | PushUsingDirective(S, UDir); | |||
9441 | } else { | |||
9442 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | |||
9443 | } | |||
9444 | ||||
9445 | if (UDir) | |||
9446 | ProcessDeclAttributeList(S, UDir, AttrList); | |||
9447 | ||||
9448 | return UDir; | |||
9449 | } | |||
9450 | ||||
9451 | void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { | |||
9452 | // If the scope has an associated entity and the using directive is at | |||
9453 | // namespace or translation unit scope, add the UsingDirectiveDecl into | |||
9454 | // its lookup structure so qualified name lookup can find it. | |||
9455 | DeclContext *Ctx = S->getEntity(); | |||
9456 | if (Ctx && !Ctx->isFunctionOrMethod()) | |||
9457 | Ctx->addDecl(UDir); | |||
9458 | else | |||
9459 | // Otherwise, it is at block scope. The using-directives will affect lookup | |||
9460 | // only to the end of the scope. | |||
9461 | S->PushUsingDirective(UDir); | |||
9462 | } | |||
9463 | ||||
9464 | Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, | |||
9465 | SourceLocation UsingLoc, | |||
9466 | SourceLocation TypenameLoc, CXXScopeSpec &SS, | |||
9467 | UnqualifiedId &Name, | |||
9468 | SourceLocation EllipsisLoc, | |||
9469 | const ParsedAttributesView &AttrList) { | |||
9470 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9470, __PRETTY_FUNCTION__)); | |||
9471 | ||||
9472 | if (SS.isEmpty()) { | |||
9473 | Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); | |||
9474 | return nullptr; | |||
9475 | } | |||
9476 | ||||
9477 | switch (Name.getKind()) { | |||
9478 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
9479 | case UnqualifiedIdKind::IK_Identifier: | |||
9480 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
9481 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
9482 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
9483 | break; | |||
9484 | ||||
9485 | case UnqualifiedIdKind::IK_ConstructorName: | |||
9486 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
9487 | // C++11 inheriting constructors. | |||
9488 | Diag(Name.getBeginLoc(), | |||
9489 | getLangOpts().CPlusPlus11 | |||
9490 | ? diag::warn_cxx98_compat_using_decl_constructor | |||
9491 | : diag::err_using_decl_constructor) | |||
9492 | << SS.getRange(); | |||
9493 | ||||
9494 | if (getLangOpts().CPlusPlus11) break; | |||
9495 | ||||
9496 | return nullptr; | |||
9497 | ||||
9498 | case UnqualifiedIdKind::IK_DestructorName: | |||
9499 | Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); | |||
9500 | return nullptr; | |||
9501 | ||||
9502 | case UnqualifiedIdKind::IK_TemplateId: | |||
9503 | Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) | |||
9504 | << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); | |||
9505 | return nullptr; | |||
9506 | ||||
9507 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
9508 | llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9508); | |||
9509 | } | |||
9510 | ||||
9511 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); | |||
9512 | DeclarationName TargetName = TargetNameInfo.getName(); | |||
9513 | if (!TargetName) | |||
9514 | return nullptr; | |||
9515 | ||||
9516 | // Warn about access declarations. | |||
9517 | if (UsingLoc.isInvalid()) { | |||
9518 | Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 | |||
9519 | ? diag::err_access_decl | |||
9520 | : diag::warn_access_decl_deprecated) | |||
9521 | << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); | |||
9522 | } | |||
9523 | ||||
9524 | if (EllipsisLoc.isInvalid()) { | |||
9525 | if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || | |||
9526 | DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) | |||
9527 | return nullptr; | |||
9528 | } else { | |||
9529 | if (!SS.getScopeRep()->containsUnexpandedParameterPack() && | |||
9530 | !TargetNameInfo.containsUnexpandedParameterPack()) { | |||
9531 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
9532 | << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); | |||
9533 | EllipsisLoc = SourceLocation(); | |||
9534 | } | |||
9535 | } | |||
9536 | ||||
9537 | NamedDecl *UD = | |||
9538 | BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, | |||
9539 | SS, TargetNameInfo, EllipsisLoc, AttrList, | |||
9540 | /*IsInstantiation*/false); | |||
9541 | if (UD) | |||
9542 | PushOnScopeChains(UD, S, /*AddToContext*/ false); | |||
9543 | ||||
9544 | return UD; | |||
9545 | } | |||
9546 | ||||
9547 | /// Determine whether a using declaration considers the given | |||
9548 | /// declarations as "equivalent", e.g., if they are redeclarations of | |||
9549 | /// the same entity or are both typedefs of the same type. | |||
9550 | static bool | |||
9551 | IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { | |||
9552 | if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) | |||
9553 | return true; | |||
9554 | ||||
9555 | if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) | |||
9556 | if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) | |||
9557 | return Context.hasSameType(TD1->getUnderlyingType(), | |||
9558 | TD2->getUnderlyingType()); | |||
9559 | ||||
9560 | return false; | |||
9561 | } | |||
9562 | ||||
9563 | ||||
9564 | /// Determines whether to create a using shadow decl for a particular | |||
9565 | /// decl, given the set of decls existing prior to this using lookup. | |||
9566 | bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, | |||
9567 | const LookupResult &Previous, | |||
9568 | UsingShadowDecl *&PrevShadow) { | |||
9569 | // Diagnose finding a decl which is not from a base class of the | |||
9570 | // current class. We do this now because there are cases where this | |||
9571 | // function will silently decide not to build a shadow decl, which | |||
9572 | // will pre-empt further diagnostics. | |||
9573 | // | |||
9574 | // We don't need to do this in C++11 because we do the check once on | |||
9575 | // the qualifier. | |||
9576 | // | |||
9577 | // FIXME: diagnose the following if we care enough: | |||
9578 | // struct A { int foo; }; | |||
9579 | // struct B : A { using A::foo; }; | |||
9580 | // template <class T> struct C : A {}; | |||
9581 | // template <class T> struct D : C<T> { using B::foo; } // <--- | |||
9582 | // This is invalid (during instantiation) in C++03 because B::foo | |||
9583 | // resolves to the using decl in B, which is not a base class of D<T>. | |||
9584 | // We can't diagnose it immediately because C<T> is an unknown | |||
9585 | // specialization. The UsingShadowDecl in D<T> then points directly | |||
9586 | // to A::foo, which will look well-formed when we instantiate. | |||
9587 | // The right solution is to not collapse the shadow-decl chain. | |||
9588 | if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { | |||
9589 | DeclContext *OrigDC = Orig->getDeclContext(); | |||
9590 | ||||
9591 | // Handle enums and anonymous structs. | |||
9592 | if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); | |||
9593 | CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); | |||
9594 | while (OrigRec->isAnonymousStructOrUnion()) | |||
9595 | OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); | |||
9596 | ||||
9597 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { | |||
9598 | if (OrigDC == CurContext) { | |||
9599 | Diag(Using->getLocation(), | |||
9600 | diag::err_using_decl_nested_name_specifier_is_current_class) | |||
9601 | << Using->getQualifierLoc().getSourceRange(); | |||
9602 | Diag(Orig->getLocation(), diag::note_using_decl_target); | |||
9603 | Using->setInvalidDecl(); | |||
9604 | return true; | |||
9605 | } | |||
9606 | ||||
9607 | Diag(Using->getQualifierLoc().getBeginLoc(), | |||
9608 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
9609 | << Using->getQualifier() | |||
9610 | << cast<CXXRecordDecl>(CurContext) | |||
9611 | << Using->getQualifierLoc().getSourceRange(); | |||
9612 | Diag(Orig->getLocation(), diag::note_using_decl_target); | |||
9613 | Using->setInvalidDecl(); | |||
9614 | return true; | |||
9615 | } | |||
9616 | } | |||
9617 | ||||
9618 | if (Previous.empty()) return false; | |||
9619 | ||||
9620 | NamedDecl *Target = Orig; | |||
9621 | if (isa<UsingShadowDecl>(Target)) | |||
9622 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | |||
9623 | ||||
9624 | // If the target happens to be one of the previous declarations, we | |||
9625 | // don't have a conflict. | |||
9626 | // | |||
9627 | // FIXME: but we might be increasing its access, in which case we | |||
9628 | // should redeclare it. | |||
9629 | NamedDecl *NonTag = nullptr, *Tag = nullptr; | |||
9630 | bool FoundEquivalentDecl = false; | |||
9631 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
9632 | I != E; ++I) { | |||
9633 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
9634 | // We can have UsingDecls in our Previous results because we use the same | |||
9635 | // LookupResult for checking whether the UsingDecl itself is a valid | |||
9636 | // redeclaration. | |||
9637 | if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) | |||
9638 | continue; | |||
9639 | ||||
9640 | if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | |||
9641 | // C++ [class.mem]p19: | |||
9642 | // If T is the name of a class, then [every named member other than | |||
9643 | // a non-static data member] shall have a name different from T | |||
9644 | if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && | |||
9645 | !isa<IndirectFieldDecl>(Target) && | |||
9646 | !isa<UnresolvedUsingValueDecl>(Target) && | |||
9647 | DiagnoseClassNameShadow( | |||
9648 | CurContext, | |||
9649 | DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) | |||
9650 | return true; | |||
9651 | } | |||
9652 | ||||
9653 | if (IsEquivalentForUsingDecl(Context, D, Target)) { | |||
9654 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) | |||
9655 | PrevShadow = Shadow; | |||
9656 | FoundEquivalentDecl = true; | |||
9657 | } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { | |||
9658 | // We don't conflict with an existing using shadow decl of an equivalent | |||
9659 | // declaration, but we're not a redeclaration of it. | |||
9660 | FoundEquivalentDecl = true; | |||
9661 | } | |||
9662 | ||||
9663 | if (isVisible(D)) | |||
9664 | (isa<TagDecl>(D) ? Tag : NonTag) = D; | |||
9665 | } | |||
9666 | ||||
9667 | if (FoundEquivalentDecl) | |||
9668 | return false; | |||
9669 | ||||
9670 | if (FunctionDecl *FD = Target->getAsFunction()) { | |||
9671 | NamedDecl *OldDecl = nullptr; | |||
9672 | switch (CheckOverload(nullptr, FD, Previous, OldDecl, | |||
9673 | /*IsForUsingDecl*/ true)) { | |||
9674 | case Ovl_Overload: | |||
9675 | return false; | |||
9676 | ||||
9677 | case Ovl_NonFunction: | |||
9678 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9679 | break; | |||
9680 | ||||
9681 | // We found a decl with the exact signature. | |||
9682 | case Ovl_Match: | |||
9683 | // If we're in a record, we want to hide the target, so we | |||
9684 | // return true (without a diagnostic) to tell the caller not to | |||
9685 | // build a shadow decl. | |||
9686 | if (CurContext->isRecord()) | |||
9687 | return true; | |||
9688 | ||||
9689 | // If we're not in a record, this is an error. | |||
9690 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9691 | break; | |||
9692 | } | |||
9693 | ||||
9694 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9695 | Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); | |||
9696 | Using->setInvalidDecl(); | |||
9697 | return true; | |||
9698 | } | |||
9699 | ||||
9700 | // Target is not a function. | |||
9701 | ||||
9702 | if (isa<TagDecl>(Target)) { | |||
9703 | // No conflict between a tag and a non-tag. | |||
9704 | if (!Tag) return false; | |||
9705 | ||||
9706 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9707 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9708 | Diag(Tag->getLocation(), diag::note_using_decl_conflict); | |||
9709 | Using->setInvalidDecl(); | |||
9710 | return true; | |||
9711 | } | |||
9712 | ||||
9713 | // No conflict between a tag and a non-tag. | |||
9714 | if (!NonTag) return false; | |||
9715 | ||||
9716 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9717 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9718 | Diag(NonTag->getLocation(), diag::note_using_decl_conflict); | |||
9719 | Using->setInvalidDecl(); | |||
9720 | return true; | |||
9721 | } | |||
9722 | ||||
9723 | /// Determine whether a direct base class is a virtual base class. | |||
9724 | static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { | |||
9725 | if (!Derived->getNumVBases()) | |||
9726 | return false; | |||
9727 | for (auto &B : Derived->bases()) | |||
9728 | if (B.getType()->getAsCXXRecordDecl() == Base) | |||
9729 | return B.isVirtual(); | |||
9730 | llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9730); | |||
9731 | } | |||
9732 | ||||
9733 | /// Builds a shadow declaration corresponding to a 'using' declaration. | |||
9734 | UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, | |||
9735 | UsingDecl *UD, | |||
9736 | NamedDecl *Orig, | |||
9737 | UsingShadowDecl *PrevDecl) { | |||
9738 | // If we resolved to another shadow declaration, just coalesce them. | |||
9739 | NamedDecl *Target = Orig; | |||
9740 | if (isa<UsingShadowDecl>(Target)) { | |||
9741 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | |||
9742 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9742, __PRETTY_FUNCTION__)); | |||
9743 | } | |||
9744 | ||||
9745 | NamedDecl *NonTemplateTarget = Target; | |||
9746 | if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) | |||
9747 | NonTemplateTarget = TargetTD->getTemplatedDecl(); | |||
9748 | ||||
9749 | UsingShadowDecl *Shadow; | |||
9750 | if (isa<CXXConstructorDecl>(NonTemplateTarget)) { | |||
9751 | bool IsVirtualBase = | |||
9752 | isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), | |||
9753 | UD->getQualifier()->getAsRecordDecl()); | |||
9754 | Shadow = ConstructorUsingShadowDecl::Create( | |||
9755 | Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); | |||
9756 | } else { | |||
9757 | Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, | |||
9758 | Target); | |||
9759 | } | |||
9760 | UD->addShadowDecl(Shadow); | |||
9761 | ||||
9762 | Shadow->setAccess(UD->getAccess()); | |||
9763 | if (Orig->isInvalidDecl() || UD->isInvalidDecl()) | |||
9764 | Shadow->setInvalidDecl(); | |||
9765 | ||||
9766 | Shadow->setPreviousDecl(PrevDecl); | |||
9767 | ||||
9768 | if (S) | |||
9769 | PushOnScopeChains(Shadow, S); | |||
9770 | else | |||
9771 | CurContext->addDecl(Shadow); | |||
9772 | ||||
9773 | ||||
9774 | return Shadow; | |||
9775 | } | |||
9776 | ||||
9777 | /// Hides a using shadow declaration. This is required by the current | |||
9778 | /// using-decl implementation when a resolvable using declaration in a | |||
9779 | /// class is followed by a declaration which would hide or override | |||
9780 | /// one or more of the using decl's targets; for example: | |||
9781 | /// | |||
9782 | /// struct Base { void foo(int); }; | |||
9783 | /// struct Derived : Base { | |||
9784 | /// using Base::foo; | |||
9785 | /// void foo(int); | |||
9786 | /// }; | |||
9787 | /// | |||
9788 | /// The governing language is C++03 [namespace.udecl]p12: | |||
9789 | /// | |||
9790 | /// When a using-declaration brings names from a base class into a | |||
9791 | /// derived class scope, member functions in the derived class | |||
9792 | /// override and/or hide member functions with the same name and | |||
9793 | /// parameter types in a base class (rather than conflicting). | |||
9794 | /// | |||
9795 | /// There are two ways to implement this: | |||
9796 | /// (1) optimistically create shadow decls when they're not hidden | |||
9797 | /// by existing declarations, or | |||
9798 | /// (2) don't create any shadow decls (or at least don't make them | |||
9799 | /// visible) until we've fully parsed/instantiated the class. | |||
9800 | /// The problem with (1) is that we might have to retroactively remove | |||
9801 | /// a shadow decl, which requires several O(n) operations because the | |||
9802 | /// decl structures are (very reasonably) not designed for removal. | |||
9803 | /// (2) avoids this but is very fiddly and phase-dependent. | |||
9804 | void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { | |||
9805 | if (Shadow->getDeclName().getNameKind() == | |||
9806 | DeclarationName::CXXConversionFunctionName) | |||
9807 | cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); | |||
9808 | ||||
9809 | // Remove it from the DeclContext... | |||
9810 | Shadow->getDeclContext()->removeDecl(Shadow); | |||
9811 | ||||
9812 | // ...and the scope, if applicable... | |||
9813 | if (S) { | |||
9814 | S->RemoveDecl(Shadow); | |||
9815 | IdResolver.RemoveDecl(Shadow); | |||
9816 | } | |||
9817 | ||||
9818 | // ...and the using decl. | |||
9819 | Shadow->getUsingDecl()->removeShadowDecl(Shadow); | |||
9820 | ||||
9821 | // TODO: complain somehow if Shadow was used. It shouldn't | |||
9822 | // be possible for this to happen, because...? | |||
9823 | } | |||
9824 | ||||
9825 | /// Find the base specifier for a base class with the given type. | |||
9826 | static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, | |||
9827 | QualType DesiredBase, | |||
9828 | bool &AnyDependentBases) { | |||
9829 | // Check whether the named type is a direct base class. | |||
9830 | CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); | |||
9831 | for (auto &Base : Derived->bases()) { | |||
9832 | CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); | |||
9833 | if (CanonicalDesiredBase == BaseType) | |||
9834 | return &Base; | |||
9835 | if (BaseType->isDependentType()) | |||
9836 | AnyDependentBases = true; | |||
9837 | } | |||
9838 | return nullptr; | |||
9839 | } | |||
9840 | ||||
9841 | namespace { | |||
9842 | class UsingValidatorCCC final : public CorrectionCandidateCallback { | |||
9843 | public: | |||
9844 | UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, | |||
9845 | NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) | |||
9846 | : HasTypenameKeyword(HasTypenameKeyword), | |||
9847 | IsInstantiation(IsInstantiation), OldNNS(NNS), | |||
9848 | RequireMemberOf(RequireMemberOf) {} | |||
9849 | ||||
9850 | bool ValidateCandidate(const TypoCorrection &Candidate) override { | |||
9851 | NamedDecl *ND = Candidate.getCorrectionDecl(); | |||
9852 | ||||
9853 | // Keywords are not valid here. | |||
9854 | if (!ND || isa<NamespaceDecl>(ND)) | |||
9855 | return false; | |||
9856 | ||||
9857 | // Completely unqualified names are invalid for a 'using' declaration. | |||
9858 | if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) | |||
9859 | return false; | |||
9860 | ||||
9861 | // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would | |||
9862 | // reject. | |||
9863 | ||||
9864 | if (RequireMemberOf) { | |||
9865 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | |||
9866 | if (FoundRecord && FoundRecord->isInjectedClassName()) { | |||
9867 | // No-one ever wants a using-declaration to name an injected-class-name | |||
9868 | // of a base class, unless they're declaring an inheriting constructor. | |||
9869 | ASTContext &Ctx = ND->getASTContext(); | |||
9870 | if (!Ctx.getLangOpts().CPlusPlus11) | |||
9871 | return false; | |||
9872 | QualType FoundType = Ctx.getRecordType(FoundRecord); | |||
9873 | ||||
9874 | // Check that the injected-class-name is named as a member of its own | |||
9875 | // type; we don't want to suggest 'using Derived::Base;', since that | |||
9876 | // means something else. | |||
9877 | NestedNameSpecifier *Specifier = | |||
9878 | Candidate.WillReplaceSpecifier() | |||
9879 | ? Candidate.getCorrectionSpecifier() | |||
9880 | : OldNNS; | |||
9881 | if (!Specifier->getAsType() || | |||
9882 | !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) | |||
9883 | return false; | |||
9884 | ||||
9885 | // Check that this inheriting constructor declaration actually names a | |||
9886 | // direct base class of the current class. | |||
9887 | bool AnyDependentBases = false; | |||
9888 | if (!findDirectBaseWithType(RequireMemberOf, | |||
9889 | Ctx.getRecordType(FoundRecord), | |||
9890 | AnyDependentBases) && | |||
9891 | !AnyDependentBases) | |||
9892 | return false; | |||
9893 | } else { | |||
9894 | auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); | |||
9895 | if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) | |||
9896 | return false; | |||
9897 | ||||
9898 | // FIXME: Check that the base class member is accessible? | |||
9899 | } | |||
9900 | } else { | |||
9901 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | |||
9902 | if (FoundRecord && FoundRecord->isInjectedClassName()) | |||
9903 | return false; | |||
9904 | } | |||
9905 | ||||
9906 | if (isa<TypeDecl>(ND)) | |||
9907 | return HasTypenameKeyword || !IsInstantiation; | |||
9908 | ||||
9909 | return !HasTypenameKeyword; | |||
9910 | } | |||
9911 | ||||
9912 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
9913 | return llvm::make_unique<UsingValidatorCCC>(*this); | |||
9914 | } | |||
9915 | ||||
9916 | private: | |||
9917 | bool HasTypenameKeyword; | |||
9918 | bool IsInstantiation; | |||
9919 | NestedNameSpecifier *OldNNS; | |||
9920 | CXXRecordDecl *RequireMemberOf; | |||
9921 | }; | |||
9922 | } // end anonymous namespace | |||
9923 | ||||
9924 | /// Builds a using declaration. | |||
9925 | /// | |||
9926 | /// \param IsInstantiation - Whether this call arises from an | |||
9927 | /// instantiation of an unresolved using declaration. We treat | |||
9928 | /// the lookup differently for these declarations. | |||
9929 | NamedDecl *Sema::BuildUsingDeclaration( | |||
9930 | Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, | |||
9931 | bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, | |||
9932 | DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, | |||
9933 | const ParsedAttributesView &AttrList, bool IsInstantiation) { | |||
9934 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast <void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9934, __PRETTY_FUNCTION__)); | |||
9935 | SourceLocation IdentLoc = NameInfo.getLoc(); | |||
9936 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9936, __PRETTY_FUNCTION__)); | |||
9937 | ||||
9938 | // FIXME: We ignore attributes for now. | |||
9939 | ||||
9940 | // For an inheriting constructor declaration, the name of the using | |||
9941 | // declaration is the name of a constructor in this class, not in the | |||
9942 | // base class. | |||
9943 | DeclarationNameInfo UsingName = NameInfo; | |||
9944 | if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) | |||
9945 | if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) | |||
9946 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | |||
9947 | Context.getCanonicalType(Context.getRecordType(RD)))); | |||
9948 | ||||
9949 | // Do the redeclaration lookup in the current scope. | |||
9950 | LookupResult Previous(*this, UsingName, LookupUsingDeclName, | |||
9951 | ForVisibleRedeclaration); | |||
9952 | Previous.setHideTags(false); | |||
9953 | if (S) { | |||
9954 | LookupName(Previous, S); | |||
9955 | ||||
9956 | // It is really dumb that we have to do this. | |||
9957 | LookupResult::Filter F = Previous.makeFilter(); | |||
9958 | while (F.hasNext()) { | |||
9959 | NamedDecl *D = F.next(); | |||
9960 | if (!isDeclInScope(D, CurContext, S)) | |||
9961 | F.erase(); | |||
9962 | // If we found a local extern declaration that's not ordinarily visible, | |||
9963 | // and this declaration is being added to a non-block scope, ignore it. | |||
9964 | // We're only checking for scope conflicts here, not also for violations | |||
9965 | // of the linkage rules. | |||
9966 | else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && | |||
9967 | !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) | |||
9968 | F.erase(); | |||
9969 | } | |||
9970 | F.done(); | |||
9971 | } else { | |||
9972 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9972, __PRETTY_FUNCTION__)); | |||
9973 | if (CurContext->isRecord()) | |||
9974 | LookupQualifiedName(Previous, CurContext); | |||
9975 | else { | |||
9976 | // No redeclaration check is needed here; in non-member contexts we | |||
9977 | // diagnosed all possible conflicts with other using-declarations when | |||
9978 | // building the template: | |||
9979 | // | |||
9980 | // For a dependent non-type using declaration, the only valid case is | |||
9981 | // if we instantiate to a single enumerator. We check for conflicts | |||
9982 | // between shadow declarations we introduce, and we check in the template | |||
9983 | // definition for conflicts between a non-type using declaration and any | |||
9984 | // other declaration, which together covers all cases. | |||
9985 | // | |||
9986 | // A dependent typename using declaration will never successfully | |||
9987 | // instantiate, since it will always name a class member, so we reject | |||
9988 | // that in the template definition. | |||
9989 | } | |||
9990 | } | |||
9991 | ||||
9992 | // Check for invalid redeclarations. | |||
9993 | if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, | |||
9994 | SS, IdentLoc, Previous)) | |||
9995 | return nullptr; | |||
9996 | ||||
9997 | // Check for bad qualifiers. | |||
9998 | if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, | |||
9999 | IdentLoc)) | |||
10000 | return nullptr; | |||
10001 | ||||
10002 | DeclContext *LookupContext = computeDeclContext(SS); | |||
10003 | NamedDecl *D; | |||
10004 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); | |||
10005 | if (!LookupContext || EllipsisLoc.isValid()) { | |||
10006 | if (HasTypenameKeyword) { | |||
10007 | // FIXME: not all declaration name kinds are legal here | |||
10008 | D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, | |||
10009 | UsingLoc, TypenameLoc, | |||
10010 | QualifierLoc, | |||
10011 | IdentLoc, NameInfo.getName(), | |||
10012 | EllipsisLoc); | |||
10013 | } else { | |||
10014 | D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, | |||
10015 | QualifierLoc, NameInfo, EllipsisLoc); | |||
10016 | } | |||
10017 | D->setAccess(AS); | |||
10018 | CurContext->addDecl(D); | |||
10019 | return D; | |||
10020 | } | |||
10021 | ||||
10022 | auto Build = [&](bool Invalid) { | |||
10023 | UsingDecl *UD = | |||
10024 | UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, | |||
10025 | UsingName, HasTypenameKeyword); | |||
10026 | UD->setAccess(AS); | |||
10027 | CurContext->addDecl(UD); | |||
10028 | UD->setInvalidDecl(Invalid); | |||
10029 | return UD; | |||
10030 | }; | |||
10031 | auto BuildInvalid = [&]{ return Build(true); }; | |||
10032 | auto BuildValid = [&]{ return Build(false); }; | |||
10033 | ||||
10034 | if (RequireCompleteDeclContext(SS, LookupContext)) | |||
10035 | return BuildInvalid(); | |||
10036 | ||||
10037 | // Look up the target name. | |||
10038 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
10039 | ||||
10040 | // Unlike most lookups, we don't always want to hide tag | |||
10041 | // declarations: tag names are visible through the using declaration | |||
10042 | // even if hidden by ordinary names, *except* in a dependent context | |||
10043 | // where it's important for the sanity of two-phase lookup. | |||
10044 | if (!IsInstantiation) | |||
10045 | R.setHideTags(false); | |||
10046 | ||||
10047 | // For the purposes of this lookup, we have a base object type | |||
10048 | // equal to that of the current context. | |||
10049 | if (CurContext->isRecord()) { | |||
10050 | R.setBaseObjectType( | |||
10051 | Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); | |||
10052 | } | |||
10053 | ||||
10054 | LookupQualifiedName(R, LookupContext); | |||
10055 | ||||
10056 | // Try to correct typos if possible. If constructor name lookup finds no | |||
10057 | // results, that means the named class has no explicit constructors, and we | |||
10058 | // suppressed declaring implicit ones (probably because it's dependent or | |||
10059 | // invalid). | |||
10060 | if (R.empty() && | |||
10061 | NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { | |||
10062 | // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes | |||
10063 | // it will believe that glibc provides a ::gets in cases where it does not, | |||
10064 | // and will try to pull it into namespace std with a using-declaration. | |||
10065 | // Just ignore the using-declaration in that case. | |||
10066 | auto *II = NameInfo.getName().getAsIdentifierInfo(); | |||
10067 | if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && | |||
10068 | CurContext->isStdNamespace() && | |||
10069 | isa<TranslationUnitDecl>(LookupContext) && | |||
10070 | getSourceManager().isInSystemHeader(UsingLoc)) | |||
10071 | return nullptr; | |||
10072 | UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), | |||
10073 | dyn_cast<CXXRecordDecl>(CurContext)); | |||
10074 | if (TypoCorrection Corrected = | |||
10075 | CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | |||
10076 | CTK_ErrorRecovery)) { | |||
10077 | // We reject candidates where DroppedSpecifier == true, hence the | |||
10078 | // literal '0' below. | |||
10079 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | |||
10080 | << NameInfo.getName() << LookupContext << 0 | |||
10081 | << SS.getRange()); | |||
10082 | ||||
10083 | // If we picked a correction with no attached Decl we can't do anything | |||
10084 | // useful with it, bail out. | |||
10085 | NamedDecl *ND = Corrected.getCorrectionDecl(); | |||
10086 | if (!ND) | |||
10087 | return BuildInvalid(); | |||
10088 | ||||
10089 | // If we corrected to an inheriting constructor, handle it as one. | |||
10090 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
10091 | if (RD && RD->isInjectedClassName()) { | |||
10092 | // The parent of the injected class name is the class itself. | |||
10093 | RD = cast<CXXRecordDecl>(RD->getParent()); | |||
10094 | ||||
10095 | // Fix up the information we'll use to build the using declaration. | |||
10096 | if (Corrected.WillReplaceSpecifier()) { | |||
10097 | NestedNameSpecifierLocBuilder Builder; | |||
10098 | Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | |||
10099 | QualifierLoc.getSourceRange()); | |||
10100 | QualifierLoc = Builder.getWithLocInContext(Context); | |||
10101 | } | |||
10102 | ||||
10103 | // In this case, the name we introduce is the name of a derived class | |||
10104 | // constructor. | |||
10105 | auto *CurClass = cast<CXXRecordDecl>(CurContext); | |||
10106 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | |||
10107 | Context.getCanonicalType(Context.getRecordType(CurClass)))); | |||
10108 | UsingName.setNamedTypeInfo(nullptr); | |||
10109 | for (auto *Ctor : LookupConstructors(RD)) | |||
10110 | R.addDecl(Ctor); | |||
10111 | R.resolveKind(); | |||
10112 | } else { | |||
10113 | // FIXME: Pick up all the declarations if we found an overloaded | |||
10114 | // function. | |||
10115 | UsingName.setName(ND->getDeclName()); | |||
10116 | R.addDecl(ND); | |||
10117 | } | |||
10118 | } else { | |||
10119 | Diag(IdentLoc, diag::err_no_member) | |||
10120 | << NameInfo.getName() << LookupContext << SS.getRange(); | |||
10121 | return BuildInvalid(); | |||
10122 | } | |||
10123 | } | |||
10124 | ||||
10125 | if (R.isAmbiguous()) | |||
10126 | return BuildInvalid(); | |||
10127 | ||||
10128 | if (HasTypenameKeyword) { | |||
10129 | // If we asked for a typename and got a non-type decl, error out. | |||
10130 | if (!R.getAsSingle<TypeDecl>()) { | |||
10131 | Diag(IdentLoc, diag::err_using_typename_non_type); | |||
10132 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) | |||
10133 | Diag((*I)->getUnderlyingDecl()->getLocation(), | |||
10134 | diag::note_using_decl_target); | |||
10135 | return BuildInvalid(); | |||
10136 | } | |||
10137 | } else { | |||
10138 | // If we asked for a non-typename and we got a type, error out, | |||
10139 | // but only if this is an instantiation of an unresolved using | |||
10140 | // decl. Otherwise just silently find the type name. | |||
10141 | if (IsInstantiation && R.getAsSingle<TypeDecl>()) { | |||
10142 | Diag(IdentLoc, diag::err_using_dependent_value_is_type); | |||
10143 | Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); | |||
10144 | return BuildInvalid(); | |||
10145 | } | |||
10146 | } | |||
10147 | ||||
10148 | // C++14 [namespace.udecl]p6: | |||
10149 | // A using-declaration shall not name a namespace. | |||
10150 | if (R.getAsSingle<NamespaceDecl>()) { | |||
10151 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) | |||
10152 | << SS.getRange(); | |||
10153 | return BuildInvalid(); | |||
10154 | } | |||
10155 | ||||
10156 | // C++14 [namespace.udecl]p7: | |||
10157 | // A using-declaration shall not name a scoped enumerator. | |||
10158 | if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { | |||
10159 | if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { | |||
10160 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) | |||
10161 | << SS.getRange(); | |||
10162 | return BuildInvalid(); | |||
10163 | } | |||
10164 | } | |||
10165 | ||||
10166 | UsingDecl *UD = BuildValid(); | |||
10167 | ||||
10168 | // Some additional rules apply to inheriting constructors. | |||
10169 | if (UsingName.getName().getNameKind() == | |||
10170 | DeclarationName::CXXConstructorName) { | |||
10171 | // Suppress access diagnostics; the access check is instead performed at the | |||
10172 | // point of use for an inheriting constructor. | |||
10173 | R.suppressDiagnostics(); | |||
10174 | if (CheckInheritingConstructorUsingDecl(UD)) | |||
10175 | return UD; | |||
10176 | } | |||
10177 | ||||
10178 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { | |||
10179 | UsingShadowDecl *PrevDecl = nullptr; | |||
10180 | if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) | |||
10181 | BuildUsingShadowDecl(S, UD, *I, PrevDecl); | |||
10182 | } | |||
10183 | ||||
10184 | return UD; | |||
10185 | } | |||
10186 | ||||
10187 | NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, | |||
10188 | ArrayRef<NamedDecl *> Expansions) { | |||
10189 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10191, __PRETTY_FUNCTION__)) | |||
10190 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10191, __PRETTY_FUNCTION__)) | |||
10191 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10191, __PRETTY_FUNCTION__)); | |||
10192 | ||||
10193 | auto *UPD = | |||
10194 | UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); | |||
10195 | UPD->setAccess(InstantiatedFrom->getAccess()); | |||
10196 | CurContext->addDecl(UPD); | |||
10197 | return UPD; | |||
10198 | } | |||
10199 | ||||
10200 | /// Additional checks for a using declaration referring to a constructor name. | |||
10201 | bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { | |||
10202 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10202, __PRETTY_FUNCTION__)); | |||
10203 | ||||
10204 | const Type *SourceType = UD->getQualifier()->getAsType(); | |||
10205 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10206, __PRETTY_FUNCTION__)) | |||
10206 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10206, __PRETTY_FUNCTION__)); | |||
10207 | CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); | |||
10208 | ||||
10209 | // Check whether the named type is a direct base class. | |||
10210 | bool AnyDependentBases = false; | |||
10211 | auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), | |||
10212 | AnyDependentBases); | |||
10213 | if (!Base && !AnyDependentBases) { | |||
10214 | Diag(UD->getUsingLoc(), | |||
10215 | diag::err_using_decl_constructor_not_in_direct_base) | |||
10216 | << UD->getNameInfo().getSourceRange() | |||
10217 | << QualType(SourceType, 0) << TargetClass; | |||
10218 | UD->setInvalidDecl(); | |||
10219 | return true; | |||
10220 | } | |||
10221 | ||||
10222 | if (Base) | |||
10223 | Base->setInheritConstructors(); | |||
10224 | ||||
10225 | return false; | |||
10226 | } | |||
10227 | ||||
10228 | /// Checks that the given using declaration is not an invalid | |||
10229 | /// redeclaration. Note that this is checking only for the using decl | |||
10230 | /// itself, not for any ill-formedness among the UsingShadowDecls. | |||
10231 | bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, | |||
10232 | bool HasTypenameKeyword, | |||
10233 | const CXXScopeSpec &SS, | |||
10234 | SourceLocation NameLoc, | |||
10235 | const LookupResult &Prev) { | |||
10236 | NestedNameSpecifier *Qual = SS.getScopeRep(); | |||
10237 | ||||
10238 | // C++03 [namespace.udecl]p8: | |||
10239 | // C++0x [namespace.udecl]p10: | |||
10240 | // A using-declaration is a declaration and can therefore be used | |||
10241 | // repeatedly where (and only where) multiple declarations are | |||
10242 | // allowed. | |||
10243 | // | |||
10244 | // That's in non-member contexts. | |||
10245 | if (!CurContext->getRedeclContext()->isRecord()) { | |||
10246 | // A dependent qualifier outside a class can only ever resolve to an | |||
10247 | // enumeration type. Therefore it conflicts with any other non-type | |||
10248 | // declaration in the same scope. | |||
10249 | // FIXME: How should we check for dependent type-type conflicts at block | |||
10250 | // scope? | |||
10251 | if (Qual->isDependent() && !HasTypenameKeyword) { | |||
10252 | for (auto *D : Prev) { | |||
10253 | if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { | |||
10254 | bool OldCouldBeEnumerator = | |||
10255 | isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); | |||
10256 | Diag(NameLoc, | |||
10257 | OldCouldBeEnumerator ? diag::err_redefinition | |||
10258 | : diag::err_redefinition_different_kind) | |||
10259 | << Prev.getLookupName(); | |||
10260 | Diag(D->getLocation(), diag::note_previous_definition); | |||
10261 | return true; | |||
10262 | } | |||
10263 | } | |||
10264 | } | |||
10265 | return false; | |||
10266 | } | |||
10267 | ||||
10268 | for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { | |||
10269 | NamedDecl *D = *I; | |||
10270 | ||||
10271 | bool DTypename; | |||
10272 | NestedNameSpecifier *DQual; | |||
10273 | if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { | |||
10274 | DTypename = UD->hasTypename(); | |||
10275 | DQual = UD->getQualifier(); | |||
10276 | } else if (UnresolvedUsingValueDecl *UD | |||
10277 | = dyn_cast<UnresolvedUsingValueDecl>(D)) { | |||
10278 | DTypename = false; | |||
10279 | DQual = UD->getQualifier(); | |||
10280 | } else if (UnresolvedUsingTypenameDecl *UD | |||
10281 | = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { | |||
10282 | DTypename = true; | |||
10283 | DQual = UD->getQualifier(); | |||
10284 | } else continue; | |||
10285 | ||||
10286 | // using decls differ if one says 'typename' and the other doesn't. | |||
10287 | // FIXME: non-dependent using decls? | |||
10288 | if (HasTypenameKeyword != DTypename) continue; | |||
10289 | ||||
10290 | // using decls differ if they name different scopes (but note that | |||
10291 | // template instantiation can cause this check to trigger when it | |||
10292 | // didn't before instantiation). | |||
10293 | if (Context.getCanonicalNestedNameSpecifier(Qual) != | |||
10294 | Context.getCanonicalNestedNameSpecifier(DQual)) | |||
10295 | continue; | |||
10296 | ||||
10297 | Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); | |||
10298 | Diag(D->getLocation(), diag::note_using_decl) << 1; | |||
10299 | return true; | |||
10300 | } | |||
10301 | ||||
10302 | return false; | |||
10303 | } | |||
10304 | ||||
10305 | ||||
10306 | /// Checks that the given nested-name qualifier used in a using decl | |||
10307 | /// in the current context is appropriately related to the current | |||
10308 | /// scope. If an error is found, diagnoses it and returns true. | |||
10309 | bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, | |||
10310 | bool HasTypename, | |||
10311 | const CXXScopeSpec &SS, | |||
10312 | const DeclarationNameInfo &NameInfo, | |||
10313 | SourceLocation NameLoc) { | |||
10314 | DeclContext *NamedContext = computeDeclContext(SS); | |||
10315 | ||||
10316 | if (!CurContext->isRecord()) { | |||
10317 | // C++03 [namespace.udecl]p3: | |||
10318 | // C++0x [namespace.udecl]p8: | |||
10319 | // A using-declaration for a class member shall be a member-declaration. | |||
10320 | ||||
10321 | // If we weren't able to compute a valid scope, it might validly be a | |||
10322 | // dependent class scope or a dependent enumeration unscoped scope. If | |||
10323 | // we have a 'typename' keyword, the scope must resolve to a class type. | |||
10324 | if ((HasTypename && !NamedContext) || | |||
10325 | (NamedContext && NamedContext->getRedeclContext()->isRecord())) { | |||
10326 | auto *RD = NamedContext | |||
10327 | ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) | |||
10328 | : nullptr; | |||
10329 | if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) | |||
10330 | RD = nullptr; | |||
10331 | ||||
10332 | Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) | |||
10333 | << SS.getRange(); | |||
10334 | ||||
10335 | // If we have a complete, non-dependent source type, try to suggest a | |||
10336 | // way to get the same effect. | |||
10337 | if (!RD) | |||
10338 | return true; | |||
10339 | ||||
10340 | // Find what this using-declaration was referring to. | |||
10341 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
10342 | R.setHideTags(false); | |||
10343 | R.suppressDiagnostics(); | |||
10344 | LookupQualifiedName(R, RD); | |||
10345 | ||||
10346 | if (R.getAsSingle<TypeDecl>()) { | |||
10347 | if (getLangOpts().CPlusPlus11) { | |||
10348 | // Convert 'using X::Y;' to 'using Y = X::Y;'. | |||
10349 | Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) | |||
10350 | << 0 // alias declaration | |||
10351 | << FixItHint::CreateInsertion(SS.getBeginLoc(), | |||
10352 | NameInfo.getName().getAsString() + | |||
10353 | " = "); | |||
10354 | } else { | |||
10355 | // Convert 'using X::Y;' to 'typedef X::Y Y;'. | |||
10356 | SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); | |||
10357 | Diag(InsertLoc, diag::note_using_decl_class_member_workaround) | |||
10358 | << 1 // typedef declaration | |||
10359 | << FixItHint::CreateReplacement(UsingLoc, "typedef") | |||
10360 | << FixItHint::CreateInsertion( | |||
10361 | InsertLoc, " " + NameInfo.getName().getAsString()); | |||
10362 | } | |||
10363 | } else if (R.getAsSingle<VarDecl>()) { | |||
10364 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | |||
10365 | // repeating the type of the static data member here. | |||
10366 | FixItHint FixIt; | |||
10367 | if (getLangOpts().CPlusPlus11) { | |||
10368 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | |||
10369 | FixIt = FixItHint::CreateReplacement( | |||
10370 | UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); | |||
10371 | } | |||
10372 | ||||
10373 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | |||
10374 | << 2 // reference declaration | |||
10375 | << FixIt; | |||
10376 | } else if (R.getAsSingle<EnumConstantDecl>()) { | |||
10377 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | |||
10378 | // repeating the type of the enumeration here, and we can't do so if | |||
10379 | // the type is anonymous. | |||
10380 | FixItHint FixIt; | |||
10381 | if (getLangOpts().CPlusPlus11) { | |||
10382 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | |||
10383 | FixIt = FixItHint::CreateReplacement( | |||
10384 | UsingLoc, | |||
10385 | "constexpr auto " + NameInfo.getName().getAsString() + " = "); | |||
10386 | } | |||
10387 | ||||
10388 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | |||
10389 | << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable | |||
10390 | << FixIt; | |||
10391 | } | |||
10392 | return true; | |||
10393 | } | |||
10394 | ||||
10395 | // Otherwise, this might be valid. | |||
10396 | return false; | |||
10397 | } | |||
10398 | ||||
10399 | // The current scope is a record. | |||
10400 | ||||
10401 | // If the named context is dependent, we can't decide much. | |||
10402 | if (!NamedContext) { | |||
10403 | // FIXME: in C++0x, we can diagnose if we can prove that the | |||
10404 | // nested-name-specifier does not refer to a base class, which is | |||
10405 | // still possible in some cases. | |||
10406 | ||||
10407 | // Otherwise we have to conservatively report that things might be | |||
10408 | // okay. | |||
10409 | return false; | |||
10410 | } | |||
10411 | ||||
10412 | if (!NamedContext->isRecord()) { | |||
10413 | // Ideally this would point at the last name in the specifier, | |||
10414 | // but we don't have that level of source info. | |||
10415 | Diag(SS.getRange().getBegin(), | |||
10416 | diag::err_using_decl_nested_name_specifier_is_not_class) | |||
10417 | << SS.getScopeRep() << SS.getRange(); | |||
10418 | return true; | |||
10419 | } | |||
10420 | ||||
10421 | if (!NamedContext->isDependentContext() && | |||
10422 | RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) | |||
10423 | return true; | |||
10424 | ||||
10425 | if (getLangOpts().CPlusPlus11) { | |||
10426 | // C++11 [namespace.udecl]p3: | |||
10427 | // In a using-declaration used as a member-declaration, the | |||
10428 | // nested-name-specifier shall name a base class of the class | |||
10429 | // being defined. | |||
10430 | ||||
10431 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( | |||
10432 | cast<CXXRecordDecl>(NamedContext))) { | |||
10433 | if (CurContext == NamedContext) { | |||
10434 | Diag(NameLoc, | |||
10435 | diag::err_using_decl_nested_name_specifier_is_current_class) | |||
10436 | << SS.getRange(); | |||
10437 | return true; | |||
10438 | } | |||
10439 | ||||
10440 | if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { | |||
10441 | Diag(SS.getRange().getBegin(), | |||
10442 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
10443 | << SS.getScopeRep() | |||
10444 | << cast<CXXRecordDecl>(CurContext) | |||
10445 | << SS.getRange(); | |||
10446 | } | |||
10447 | return true; | |||
10448 | } | |||
10449 | ||||
10450 | return false; | |||
10451 | } | |||
10452 | ||||
10453 | // C++03 [namespace.udecl]p4: | |||
10454 | // A using-declaration used as a member-declaration shall refer | |||
10455 | // to a member of a base class of the class being defined [etc.]. | |||
10456 | ||||
10457 | // Salient point: SS doesn't have to name a base class as long as | |||
10458 | // lookup only finds members from base classes. Therefore we can | |||
10459 | // diagnose here only if we can prove that that can't happen, | |||
10460 | // i.e. if the class hierarchies provably don't intersect. | |||
10461 | ||||
10462 | // TODO: it would be nice if "definitely valid" results were cached | |||
10463 | // in the UsingDecl and UsingShadowDecl so that these checks didn't | |||
10464 | // need to be repeated. | |||
10465 | ||||
10466 | llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; | |||
10467 | auto Collect = [&Bases](const CXXRecordDecl *Base) { | |||
10468 | Bases.insert(Base); | |||
10469 | return true; | |||
10470 | }; | |||
10471 | ||||
10472 | // Collect all bases. Return false if we find a dependent base. | |||
10473 | if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) | |||
10474 | return false; | |||
10475 | ||||
10476 | // Returns true if the base is dependent or is one of the accumulated base | |||
10477 | // classes. | |||
10478 | auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { | |||
10479 | return !Bases.count(Base); | |||
10480 | }; | |||
10481 | ||||
10482 | // Return false if the class has a dependent base or if it or one | |||
10483 | // of its bases is present in the base set of the current context. | |||
10484 | if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || | |||
10485 | !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) | |||
10486 | return false; | |||
10487 | ||||
10488 | Diag(SS.getRange().getBegin(), | |||
10489 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
10490 | << SS.getScopeRep() | |||
10491 | << cast<CXXRecordDecl>(CurContext) | |||
10492 | << SS.getRange(); | |||
10493 | ||||
10494 | return true; | |||
10495 | } | |||
10496 | ||||
10497 | Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, | |||
10498 | MultiTemplateParamsArg TemplateParamLists, | |||
10499 | SourceLocation UsingLoc, UnqualifiedId &Name, | |||
10500 | const ParsedAttributesView &AttrList, | |||
10501 | TypeResult Type, Decl *DeclFromDeclSpec) { | |||
10502 | // Skip up to the relevant declaration scope. | |||
10503 | while (S->isTemplateParamScope()) | |||
10504 | S = S->getParent(); | |||
10505 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10506, __PRETTY_FUNCTION__)) | |||
10506 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10506, __PRETTY_FUNCTION__)); | |||
10507 | ||||
10508 | if (Type.isInvalid()) | |||
10509 | return nullptr; | |||
10510 | ||||
10511 | bool Invalid = false; | |||
10512 | DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); | |||
10513 | TypeSourceInfo *TInfo = nullptr; | |||
10514 | GetTypeFromParser(Type.get(), &TInfo); | |||
10515 | ||||
10516 | if (DiagnoseClassNameShadow(CurContext, NameInfo)) | |||
10517 | return nullptr; | |||
10518 | ||||
10519 | if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, | |||
10520 | UPPC_DeclarationType)) { | |||
10521 | Invalid = true; | |||
10522 | TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, | |||
10523 | TInfo->getTypeLoc().getBeginLoc()); | |||
10524 | } | |||
10525 | ||||
10526 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
10527 | TemplateParamLists.size() | |||
10528 | ? forRedeclarationInCurContext() | |||
10529 | : ForVisibleRedeclaration); | |||
10530 | LookupName(Previous, S); | |||
10531 | ||||
10532 | // Warn about shadowing the name of a template parameter. | |||
10533 | if (Previous.isSingleResult() && | |||
10534 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
10535 | DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); | |||
10536 | Previous.clear(); | |||
10537 | } | |||
10538 | ||||
10539 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10540, __PRETTY_FUNCTION__)) | |||
10540 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10540, __PRETTY_FUNCTION__)); | |||
10541 | TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, | |||
10542 | Name.StartLocation, | |||
10543 | Name.Identifier, TInfo); | |||
10544 | ||||
10545 | NewTD->setAccess(AS); | |||
10546 | ||||
10547 | if (Invalid) | |||
10548 | NewTD->setInvalidDecl(); | |||
10549 | ||||
10550 | ProcessDeclAttributeList(S, NewTD, AttrList); | |||
10551 | AddPragmaAttributes(S, NewTD); | |||
10552 | ||||
10553 | CheckTypedefForVariablyModifiedType(S, NewTD); | |||
10554 | Invalid |= NewTD->isInvalidDecl(); | |||
10555 | ||||
10556 | bool Redeclaration = false; | |||
10557 | ||||
10558 | NamedDecl *NewND; | |||
10559 | if (TemplateParamLists.size()) { | |||
10560 | TypeAliasTemplateDecl *OldDecl = nullptr; | |||
10561 | TemplateParameterList *OldTemplateParams = nullptr; | |||
10562 | ||||
10563 | if (TemplateParamLists.size() != 1) { | |||
10564 | Diag(UsingLoc, diag::err_alias_template_extra_headers) | |||
10565 | << SourceRange(TemplateParamLists[1]->getTemplateLoc(), | |||
10566 | TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); | |||
10567 | } | |||
10568 | TemplateParameterList *TemplateParams = TemplateParamLists[0]; | |||
10569 | ||||
10570 | // Check that we can declare a template here. | |||
10571 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
10572 | return nullptr; | |||
10573 | ||||
10574 | // Only consider previous declarations in the same scope. | |||
10575 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, | |||
10576 | /*ExplicitInstantiationOrSpecialization*/false); | |||
10577 | if (!Previous.empty()) { | |||
10578 | Redeclaration = true; | |||
10579 | ||||
10580 | OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); | |||
10581 | if (!OldDecl && !Invalid) { | |||
10582 | Diag(UsingLoc, diag::err_redefinition_different_kind) | |||
10583 | << Name.Identifier; | |||
10584 | ||||
10585 | NamedDecl *OldD = Previous.getRepresentativeDecl(); | |||
10586 | if (OldD->getLocation().isValid()) | |||
10587 | Diag(OldD->getLocation(), diag::note_previous_definition); | |||
10588 | ||||
10589 | Invalid = true; | |||
10590 | } | |||
10591 | ||||
10592 | if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { | |||
10593 | if (TemplateParameterListsAreEqual(TemplateParams, | |||
10594 | OldDecl->getTemplateParameters(), | |||
10595 | /*Complain=*/true, | |||
10596 | TPL_TemplateMatch)) | |||
10597 | OldTemplateParams = | |||
10598 | OldDecl->getMostRecentDecl()->getTemplateParameters(); | |||
10599 | else | |||
10600 | Invalid = true; | |||
10601 | ||||
10602 | TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); | |||
10603 | if (!Invalid && | |||
10604 | !Context.hasSameType(OldTD->getUnderlyingType(), | |||
10605 | NewTD->getUnderlyingType())) { | |||
10606 | // FIXME: The C++0x standard does not clearly say this is ill-formed, | |||
10607 | // but we can't reasonably accept it. | |||
10608 | Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) | |||
10609 | << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); | |||
10610 | if (OldTD->getLocation().isValid()) | |||
10611 | Diag(OldTD->getLocation(), diag::note_previous_definition); | |||
10612 | Invalid = true; | |||
10613 | } | |||
10614 | } | |||
10615 | } | |||
10616 | ||||
10617 | // Merge any previous default template arguments into our parameters, | |||
10618 | // and check the parameter list. | |||
10619 | if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, | |||
10620 | TPC_TypeAliasTemplate)) | |||
10621 | return nullptr; | |||
10622 | ||||
10623 | TypeAliasTemplateDecl *NewDecl = | |||
10624 | TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, | |||
10625 | Name.Identifier, TemplateParams, | |||
10626 | NewTD); | |||
10627 | NewTD->setDescribedAliasTemplate(NewDecl); | |||
10628 | ||||
10629 | NewDecl->setAccess(AS); | |||
10630 | ||||
10631 | if (Invalid) | |||
10632 | NewDecl->setInvalidDecl(); | |||
10633 | else if (OldDecl) { | |||
10634 | NewDecl->setPreviousDecl(OldDecl); | |||
10635 | CheckRedeclarationModuleOwnership(NewDecl, OldDecl); | |||
10636 | } | |||
10637 | ||||
10638 | NewND = NewDecl; | |||
10639 | } else { | |||
10640 | if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { | |||
10641 | setTagNameForLinkagePurposes(TD, NewTD); | |||
10642 | handleTagNumbering(TD, S); | |||
10643 | } | |||
10644 | ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); | |||
10645 | NewND = NewTD; | |||
10646 | } | |||
10647 | ||||
10648 | PushOnScopeChains(NewND, S); | |||
10649 | ActOnDocumentableDecl(NewND); | |||
10650 | return NewND; | |||
10651 | } | |||
10652 | ||||
10653 | Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, | |||
10654 | SourceLocation AliasLoc, | |||
10655 | IdentifierInfo *Alias, CXXScopeSpec &SS, | |||
10656 | SourceLocation IdentLoc, | |||
10657 | IdentifierInfo *Ident) { | |||
10658 | ||||
10659 | // Lookup the namespace name. | |||
10660 | LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); | |||
10661 | LookupParsedName(R, S, &SS); | |||
10662 | ||||
10663 | if (R.isAmbiguous()) | |||
10664 | return nullptr; | |||
10665 | ||||
10666 | if (R.empty()) { | |||
10667 | if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { | |||
10668 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | |||
10669 | return nullptr; | |||
10670 | } | |||
10671 | } | |||
10672 | assert(!R.isAmbiguous() && !R.empty())((!R.isAmbiguous() && !R.empty()) ? static_cast<void > (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10672, __PRETTY_FUNCTION__)); | |||
10673 | NamedDecl *ND = R.getRepresentativeDecl(); | |||
10674 | ||||
10675 | // Check if we have a previous declaration with the same name. | |||
10676 | LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, | |||
10677 | ForVisibleRedeclaration); | |||
10678 | LookupName(PrevR, S); | |||
10679 | ||||
10680 | // Check we're not shadowing a template parameter. | |||
10681 | if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { | |||
10682 | DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); | |||
10683 | PrevR.clear(); | |||
10684 | } | |||
10685 | ||||
10686 | // Filter out any other lookup result from an enclosing scope. | |||
10687 | FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, | |||
10688 | /*AllowInlineNamespace*/false); | |||
10689 | ||||
10690 | // Find the previous declaration and check that we can redeclare it. | |||
10691 | NamespaceAliasDecl *Prev = nullptr; | |||
10692 | if (PrevR.isSingleResult()) { | |||
10693 | NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); | |||
10694 | if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { | |||
10695 | // We already have an alias with the same name that points to the same | |||
10696 | // namespace; check that it matches. | |||
10697 | if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { | |||
10698 | Prev = AD; | |||
10699 | } else if (isVisible(PrevDecl)) { | |||
10700 | Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) | |||
10701 | << Alias; | |||
10702 | Diag(AD->getLocation(), diag::note_previous_namespace_alias) | |||
10703 | << AD->getNamespace(); | |||
10704 | return nullptr; | |||
10705 | } | |||
10706 | } else if (isVisible(PrevDecl)) { | |||
10707 | unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) | |||
10708 | ? diag::err_redefinition | |||
10709 | : diag::err_redefinition_different_kind; | |||
10710 | Diag(AliasLoc, DiagID) << Alias; | |||
10711 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
10712 | return nullptr; | |||
10713 | } | |||
10714 | } | |||
10715 | ||||
10716 | // The use of a nested name specifier may trigger deprecation warnings. | |||
10717 | DiagnoseUseOfDecl(ND, IdentLoc); | |||
10718 | ||||
10719 | NamespaceAliasDecl *AliasDecl = | |||
10720 | NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, | |||
10721 | Alias, SS.getWithLocInContext(Context), | |||
10722 | IdentLoc, ND); | |||
10723 | if (Prev) | |||
10724 | AliasDecl->setPreviousDecl(Prev); | |||
10725 | ||||
10726 | PushOnScopeChains(AliasDecl, S); | |||
10727 | return AliasDecl; | |||
10728 | } | |||
10729 | ||||
10730 | namespace { | |||
10731 | struct SpecialMemberExceptionSpecInfo | |||
10732 | : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { | |||
10733 | SourceLocation Loc; | |||
10734 | Sema::ImplicitExceptionSpecification ExceptSpec; | |||
10735 | ||||
10736 | SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, | |||
10737 | Sema::CXXSpecialMember CSM, | |||
10738 | Sema::InheritedConstructorInfo *ICI, | |||
10739 | SourceLocation Loc) | |||
10740 | : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} | |||
10741 | ||||
10742 | bool visitBase(CXXBaseSpecifier *Base); | |||
10743 | bool visitField(FieldDecl *FD); | |||
10744 | ||||
10745 | void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | |||
10746 | unsigned Quals); | |||
10747 | ||||
10748 | void visitSubobjectCall(Subobject Subobj, | |||
10749 | Sema::SpecialMemberOverloadResult SMOR); | |||
10750 | }; | |||
10751 | } | |||
10752 | ||||
10753 | bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { | |||
10754 | auto *RT = Base->getType()->getAs<RecordType>(); | |||
10755 | if (!RT) | |||
10756 | return false; | |||
10757 | ||||
10758 | auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); | |||
10759 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | |||
10760 | if (auto *BaseCtor = SMOR.getMethod()) { | |||
10761 | visitSubobjectCall(Base, BaseCtor); | |||
10762 | return false; | |||
10763 | } | |||
10764 | ||||
10765 | visitClassSubobject(BaseClass, Base, 0); | |||
10766 | return false; | |||
10767 | } | |||
10768 | ||||
10769 | bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { | |||
10770 | if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { | |||
10771 | Expr *E = FD->getInClassInitializer(); | |||
10772 | if (!E) | |||
10773 | // FIXME: It's a little wasteful to build and throw away a | |||
10774 | // CXXDefaultInitExpr here. | |||
10775 | // FIXME: We should have a single context note pointing at Loc, and | |||
10776 | // this location should be MD->getLocation() instead, since that's | |||
10777 | // the location where we actually use the default init expression. | |||
10778 | E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); | |||
10779 | if (E) | |||
10780 | ExceptSpec.CalledExpr(E); | |||
10781 | } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) | |||
10782 | ->getAs<RecordType>()) { | |||
10783 | visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, | |||
10784 | FD->getType().getCVRQualifiers()); | |||
10785 | } | |||
10786 | return false; | |||
10787 | } | |||
10788 | ||||
10789 | void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, | |||
10790 | Subobject Subobj, | |||
10791 | unsigned Quals) { | |||
10792 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
10793 | bool IsMutable = Field && Field->isMutable(); | |||
10794 | visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); | |||
10795 | } | |||
10796 | ||||
10797 | void SpecialMemberExceptionSpecInfo::visitSubobjectCall( | |||
10798 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { | |||
10799 | // Note, if lookup fails, it doesn't matter what exception specification we | |||
10800 | // choose because the special member will be deleted. | |||
10801 | if (CXXMethodDecl *MD = SMOR.getMethod()) | |||
10802 | ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); | |||
10803 | } | |||
10804 | ||||
10805 | namespace { | |||
10806 | /// RAII object to register a special member as being currently declared. | |||
10807 | struct ComputingExceptionSpec { | |||
10808 | Sema &S; | |||
10809 | ||||
10810 | ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) | |||
10811 | : S(S) { | |||
10812 | Sema::CodeSynthesisContext Ctx; | |||
10813 | Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; | |||
10814 | Ctx.PointOfInstantiation = Loc; | |||
10815 | Ctx.Entity = MD; | |||
10816 | S.pushCodeSynthesisContext(Ctx); | |||
10817 | } | |||
10818 | ~ComputingExceptionSpec() { | |||
10819 | S.popCodeSynthesisContext(); | |||
10820 | } | |||
10821 | }; | |||
10822 | } | |||
10823 | ||||
10824 | bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { | |||
10825 | llvm::APSInt Result; | |||
10826 | ExprResult Converted = CheckConvertedConstantExpression( | |||
10827 | ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); | |||
10828 | ExplicitSpec.setExpr(Converted.get()); | |||
10829 | if (Converted.isUsable() && !Converted.get()->isValueDependent()) { | |||
10830 | ExplicitSpec.setKind(Result.getBoolValue() | |||
10831 | ? ExplicitSpecKind::ResolvedTrue | |||
10832 | : ExplicitSpecKind::ResolvedFalse); | |||
10833 | return true; | |||
10834 | } | |||
10835 | ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); | |||
10836 | return false; | |||
10837 | } | |||
10838 | ||||
10839 | ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { | |||
10840 | ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); | |||
10841 | if (!ExplicitExpr->isTypeDependent()) | |||
10842 | tryResolveExplicitSpecifier(ES); | |||
10843 | return ES; | |||
10844 | } | |||
10845 | ||||
10846 | static Sema::ImplicitExceptionSpecification | |||
10847 | ComputeDefaultedSpecialMemberExceptionSpec( | |||
10848 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
10849 | Sema::InheritedConstructorInfo *ICI) { | |||
10850 | ComputingExceptionSpec CES(S, MD, Loc); | |||
10851 | ||||
10852 | CXXRecordDecl *ClassDecl = MD->getParent(); | |||
10853 | ||||
10854 | // C++ [except.spec]p14: | |||
10855 | // An implicitly declared special member function (Clause 12) shall have an | |||
10856 | // exception-specification. [...] | |||
10857 | SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); | |||
10858 | if (ClassDecl->isInvalidDecl()) | |||
10859 | return Info.ExceptSpec; | |||
10860 | ||||
10861 | // FIXME: If this diagnostic fires, we're probably missing a check for | |||
10862 | // attempting to resolve an exception specification before it's known | |||
10863 | // at a higher level. | |||
10864 | if (S.RequireCompleteType(MD->getLocation(), | |||
10865 | S.Context.getRecordType(ClassDecl), | |||
10866 | diag::err_exception_spec_incomplete_type)) | |||
10867 | return Info.ExceptSpec; | |||
10868 | ||||
10869 | // C++1z [except.spec]p7: | |||
10870 | // [Look for exceptions thrown by] a constructor selected [...] to | |||
10871 | // initialize a potentially constructed subobject, | |||
10872 | // C++1z [except.spec]p8: | |||
10873 | // The exception specification for an implicitly-declared destructor, or a | |||
10874 | // destructor without a noexcept-specifier, is potentially-throwing if and | |||
10875 | // only if any of the destructors for any of its potentially constructed | |||
10876 | // subojects is potentially throwing. | |||
10877 | // FIXME: We respect the first rule but ignore the "potentially constructed" | |||
10878 | // in the second rule to resolve a core issue (no number yet) that would have | |||
10879 | // us reject: | |||
10880 | // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; | |||
10881 | // struct B : A {}; | |||
10882 | // struct C : B { void f(); }; | |||
10883 | // ... due to giving B::~B() a non-throwing exception specification. | |||
10884 | Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases | |||
10885 | : Info.VisitAllBases); | |||
10886 | ||||
10887 | return Info.ExceptSpec; | |||
10888 | } | |||
10889 | ||||
10890 | namespace { | |||
10891 | /// RAII object to register a special member as being currently declared. | |||
10892 | struct DeclaringSpecialMember { | |||
10893 | Sema &S; | |||
10894 | Sema::SpecialMemberDecl D; | |||
10895 | Sema::ContextRAII SavedContext; | |||
10896 | bool WasAlreadyBeingDeclared; | |||
10897 | ||||
10898 | DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) | |||
10899 | : S(S), D(RD, CSM), SavedContext(S, RD) { | |||
10900 | WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; | |||
10901 | if (WasAlreadyBeingDeclared) | |||
10902 | // This almost never happens, but if it does, ensure that our cache | |||
10903 | // doesn't contain a stale result. | |||
10904 | S.SpecialMemberCache.clear(); | |||
10905 | else { | |||
10906 | // Register a note to be produced if we encounter an error while | |||
10907 | // declaring the special member. | |||
10908 | Sema::CodeSynthesisContext Ctx; | |||
10909 | Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; | |||
10910 | // FIXME: We don't have a location to use here. Using the class's | |||
10911 | // location maintains the fiction that we declare all special members | |||
10912 | // with the class, but (1) it's not clear that lying about that helps our | |||
10913 | // users understand what's going on, and (2) there may be outer contexts | |||
10914 | // on the stack (some of which are relevant) and printing them exposes | |||
10915 | // our lies. | |||
10916 | Ctx.PointOfInstantiation = RD->getLocation(); | |||
10917 | Ctx.Entity = RD; | |||
10918 | Ctx.SpecialMember = CSM; | |||
10919 | S.pushCodeSynthesisContext(Ctx); | |||
10920 | } | |||
10921 | } | |||
10922 | ~DeclaringSpecialMember() { | |||
10923 | if (!WasAlreadyBeingDeclared) { | |||
10924 | S.SpecialMembersBeingDeclared.erase(D); | |||
10925 | S.popCodeSynthesisContext(); | |||
10926 | } | |||
10927 | } | |||
10928 | ||||
10929 | /// Are we already trying to declare this special member? | |||
10930 | bool isAlreadyBeingDeclared() const { | |||
10931 | return WasAlreadyBeingDeclared; | |||
10932 | } | |||
10933 | }; | |||
10934 | } | |||
10935 | ||||
10936 | void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { | |||
10937 | // Look up any existing declarations, but don't trigger declaration of all | |||
10938 | // implicit special members with this name. | |||
10939 | DeclarationName Name = FD->getDeclName(); | |||
10940 | LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, | |||
10941 | ForExternalRedeclaration); | |||
10942 | for (auto *D : FD->getParent()->lookup(Name)) | |||
10943 | if (auto *Acceptable = R.getAcceptableDecl(D)) | |||
10944 | R.addDecl(Acceptable); | |||
10945 | R.resolveKind(); | |||
10946 | R.suppressDiagnostics(); | |||
10947 | ||||
10948 | CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); | |||
10949 | } | |||
10950 | ||||
10951 | void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, | |||
10952 | QualType ResultTy, | |||
10953 | ArrayRef<QualType> Args) { | |||
10954 | // Build an exception specification pointing back at this constructor. | |||
10955 | FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); | |||
10956 | ||||
10957 | if (getLangOpts().OpenCLCPlusPlus) { | |||
10958 | // OpenCL: Implicitly defaulted special member are of the generic address | |||
10959 | // space. | |||
10960 | EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); | |||
10961 | } | |||
10962 | ||||
10963 | auto QT = Context.getFunctionType(ResultTy, Args, EPI); | |||
10964 | SpecialMem->setType(QT); | |||
10965 | } | |||
10966 | ||||
10967 | CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( | |||
10968 | CXXRecordDecl *ClassDecl) { | |||
10969 | // C++ [class.ctor]p5: | |||
10970 | // A default constructor for a class X is a constructor of class X | |||
10971 | // that can be called without an argument. If there is no | |||
10972 | // user-declared constructor for class X, a default constructor is | |||
10973 | // implicitly declared. An implicitly-declared default constructor | |||
10974 | // is an inline public member of its class. | |||
10975 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10976, __PRETTY_FUNCTION__)) | |||
10976 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10976, __PRETTY_FUNCTION__)); | |||
10977 | ||||
10978 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); | |||
10979 | if (DSM.isAlreadyBeingDeclared()) | |||
10980 | return nullptr; | |||
10981 | ||||
10982 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
10983 | CXXDefaultConstructor, | |||
10984 | false); | |||
10985 | ||||
10986 | // Create the actual constructor declaration. | |||
10987 | CanQualType ClassType | |||
10988 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
10989 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
10990 | DeclarationName Name | |||
10991 | = Context.DeclarationNames.getCXXConstructorName(ClassType); | |||
10992 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
10993 | CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( | |||
10994 | Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), | |||
10995 | /*TInfo=*/nullptr, ExplicitSpecifier(), | |||
10996 | /*isInline=*/true, /*isImplicitlyDeclared=*/true, Constexpr); | |||
10997 | DefaultCon->setAccess(AS_public); | |||
10998 | DefaultCon->setDefaulted(); | |||
10999 | ||||
11000 | if (getLangOpts().CUDA) { | |||
11001 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, | |||
11002 | DefaultCon, | |||
11003 | /* ConstRHS */ false, | |||
11004 | /* Diagnose */ false); | |||
11005 | } | |||
11006 | ||||
11007 | setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); | |||
11008 | ||||
11009 | // We don't need to use SpecialMemberIsTrivial here; triviality for default | |||
11010 | // constructors is easy to compute. | |||
11011 | DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); | |||
11012 | ||||
11013 | // Note that we have declared this constructor. | |||
11014 | ++getASTContext().NumImplicitDefaultConstructorsDeclared; | |||
11015 | ||||
11016 | Scope *S = getScopeForContext(ClassDecl); | |||
11017 | CheckImplicitSpecialMemberDeclaration(S, DefaultCon); | |||
11018 | ||||
11019 | if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) | |||
11020 | SetDeclDeleted(DefaultCon, ClassLoc); | |||
11021 | ||||
11022 | if (S) | |||
11023 | PushOnScopeChains(DefaultCon, S, false); | |||
11024 | ClassDecl->addDecl(DefaultCon); | |||
11025 | ||||
11026 | return DefaultCon; | |||
11027 | } | |||
11028 | ||||
11029 | void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, | |||
11030 | CXXConstructorDecl *Constructor) { | |||
11031 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11034, __PRETTY_FUNCTION__)) | |||
11032 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11034, __PRETTY_FUNCTION__)) | |||
11033 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11034, __PRETTY_FUNCTION__)) | |||
11034 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11034, __PRETTY_FUNCTION__)); | |||
11035 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | |||
11036 | return; | |||
11037 | ||||
11038 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
11039 | assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")((ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11039, __PRETTY_FUNCTION__)); | |||
11040 | ||||
11041 | SynthesizedFunctionScope Scope(*this, Constructor); | |||
11042 | ||||
11043 | // The exception specification is needed because we are defining the | |||
11044 | // function. | |||
11045 | ResolveExceptionSpec(CurrentLocation, | |||
11046 | Constructor->getType()->castAs<FunctionProtoType>()); | |||
11047 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
11048 | ||||
11049 | // Add a context note for diagnostics produced after this point. | |||
11050 | Scope.addContextNote(CurrentLocation); | |||
11051 | ||||
11052 | if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { | |||
11053 | Constructor->setInvalidDecl(); | |||
11054 | return; | |||
11055 | } | |||
11056 | ||||
11057 | SourceLocation Loc = Constructor->getEndLoc().isValid() | |||
11058 | ? Constructor->getEndLoc() | |||
11059 | : Constructor->getLocation(); | |||
11060 | Constructor->setBody(new (Context) CompoundStmt(Loc)); | |||
11061 | Constructor->markUsed(Context); | |||
11062 | ||||
11063 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
11064 | L->CompletedImplicitDefinition(Constructor); | |||
11065 | } | |||
11066 | ||||
11067 | DiagnoseUninitializedFields(*this, Constructor); | |||
11068 | } | |||
11069 | ||||
11070 | void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { | |||
11071 | // Perform any delayed checks on exception specifications. | |||
11072 | CheckDelayedMemberExceptionSpecs(); | |||
11073 | } | |||
11074 | ||||
11075 | /// Find or create the fake constructor we synthesize to model constructing an | |||
11076 | /// object of a derived class via a constructor of a base class. | |||
11077 | CXXConstructorDecl * | |||
11078 | Sema::findInheritingConstructor(SourceLocation Loc, | |||
11079 | CXXConstructorDecl *BaseCtor, | |||
11080 | ConstructorUsingShadowDecl *Shadow) { | |||
11081 | CXXRecordDecl *Derived = Shadow->getParent(); | |||
11082 | SourceLocation UsingLoc = Shadow->getLocation(); | |||
11083 | ||||
11084 | // FIXME: Add a new kind of DeclarationName for an inherited constructor. | |||
11085 | // For now we use the name of the base class constructor as a member of the | |||
11086 | // derived class to indicate a (fake) inherited constructor name. | |||
11087 | DeclarationName Name = BaseCtor->getDeclName(); | |||
11088 | ||||
11089 | // Check to see if we already have a fake constructor for this inherited | |||
11090 | // constructor call. | |||
11091 | for (NamedDecl *Ctor : Derived->lookup(Name)) | |||
11092 | if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) | |||
11093 | ->getInheritedConstructor() | |||
11094 | .getConstructor(), | |||
11095 | BaseCtor)) | |||
11096 | return cast<CXXConstructorDecl>(Ctor); | |||
11097 | ||||
11098 | DeclarationNameInfo NameInfo(Name, UsingLoc); | |||
11099 | TypeSourceInfo *TInfo = | |||
11100 | Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); | |||
11101 | FunctionProtoTypeLoc ProtoLoc = | |||
11102 | TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); | |||
11103 | ||||
11104 | // Check the inherited constructor is valid and find the list of base classes | |||
11105 | // from which it was inherited. | |||
11106 | InheritedConstructorInfo ICI(*this, Loc, Shadow); | |||
11107 | ||||
11108 | bool Constexpr = | |||
11109 | BaseCtor->isConstexpr() && | |||
11110 | defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, | |||
11111 | false, BaseCtor, &ICI); | |||
11112 | ||||
11113 | CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( | |||
11114 | Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, | |||
11115 | BaseCtor->getExplicitSpecifier(), /*Inline=*/true, | |||
11116 | /*ImplicitlyDeclared=*/true, Constexpr, | |||
11117 | InheritedConstructor(Shadow, BaseCtor)); | |||
11118 | if (Shadow->isInvalidDecl()) | |||
11119 | DerivedCtor->setInvalidDecl(); | |||
11120 | ||||
11121 | // Build an unevaluated exception specification for this fake constructor. | |||
11122 | const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); | |||
11123 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
11124 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
11125 | EPI.ExceptionSpec.SourceDecl = DerivedCtor; | |||
11126 | DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), | |||
11127 | FPT->getParamTypes(), EPI)); | |||
11128 | ||||
11129 | // Build the parameter declarations. | |||
11130 | SmallVector<ParmVarDecl *, 16> ParamDecls; | |||
11131 | for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { | |||
11132 | TypeSourceInfo *TInfo = | |||
11133 | Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); | |||
11134 | ParmVarDecl *PD = ParmVarDecl::Create( | |||
11135 | Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, | |||
11136 | FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); | |||
11137 | PD->setScopeInfo(0, I); | |||
11138 | PD->setImplicit(); | |||
11139 | // Ensure attributes are propagated onto parameters (this matters for | |||
11140 | // format, pass_object_size, ...). | |||
11141 | mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); | |||
11142 | ParamDecls.push_back(PD); | |||
11143 | ProtoLoc.setParam(I, PD); | |||
11144 | } | |||
11145 | ||||
11146 | // Set up the new constructor. | |||
11147 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11147, __PRETTY_FUNCTION__)); | |||
11148 | DerivedCtor->setAccess(BaseCtor->getAccess()); | |||
11149 | DerivedCtor->setParams(ParamDecls); | |||
11150 | Derived->addDecl(DerivedCtor); | |||
11151 | ||||
11152 | if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) | |||
11153 | SetDeclDeleted(DerivedCtor, UsingLoc); | |||
11154 | ||||
11155 | return DerivedCtor; | |||
11156 | } | |||
11157 | ||||
11158 | void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { | |||
11159 | InheritedConstructorInfo ICI(*this, Ctor->getLocation(), | |||
11160 | Ctor->getInheritedConstructor().getShadowDecl()); | |||
11161 | ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, | |||
11162 | /*Diagnose*/true); | |||
11163 | } | |||
11164 | ||||
11165 | void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, | |||
11166 | CXXConstructorDecl *Constructor) { | |||
11167 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
11168 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11170, __PRETTY_FUNCTION__)) | |||
| ||||
11169 | !Constructor->doesThisDeclarationHaveABody() &&((Constructor->getInheritedConstructor() && !Constructor ->doesThisDeclarationHaveABody() && !Constructor-> isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11170, __PRETTY_FUNCTION__)) | |||
11170 | !Constructor->isDeleted())((Constructor->getInheritedConstructor() && !Constructor ->doesThisDeclarationHaveABody() && !Constructor-> isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11170, __PRETTY_FUNCTION__)); | |||
11171 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | |||
11172 | return; | |||
11173 | ||||
11174 | // Initializations are performed "as if by a defaulted default constructor", | |||
11175 | // so enter the appropriate scope. | |||
11176 | SynthesizedFunctionScope Scope(*this, Constructor); | |||
11177 | ||||
11178 | // The exception specification is needed because we are defining the | |||
11179 | // function. | |||
11180 | ResolveExceptionSpec(CurrentLocation, | |||
11181 | Constructor->getType()->castAs<FunctionProtoType>()); | |||
11182 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
11183 | ||||
11184 | // Add a context note for diagnostics produced after this point. | |||
11185 | Scope.addContextNote(CurrentLocation); | |||
11186 | ||||
11187 | ConstructorUsingShadowDecl *Shadow = | |||
11188 | Constructor->getInheritedConstructor().getShadowDecl(); | |||
11189 | CXXConstructorDecl *InheritedCtor = | |||
11190 | Constructor->getInheritedConstructor().getConstructor(); | |||
11191 | ||||
11192 | // [class.inhctor.init]p1: | |||
11193 | // initialization proceeds as if a defaulted default constructor is used to | |||
11194 | // initialize the D object and each base class subobject from which the | |||
11195 | // constructor was inherited | |||
11196 | ||||
11197 | InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); | |||
11198 | CXXRecordDecl *RD = Shadow->getParent(); | |||
11199 | SourceLocation InitLoc = Shadow->getLocation(); | |||
11200 | ||||
11201 | // Build explicit initializers for all base classes from which the | |||
11202 | // constructor was inherited. | |||
11203 | SmallVector<CXXCtorInitializer*, 8> Inits; | |||
11204 | for (bool VBase : {false, true}) { | |||
11205 | for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { | |||
11206 | if (B.isVirtual() != VBase) | |||
11207 | continue; | |||
11208 | ||||
11209 | auto *BaseRD = B.getType()->getAsCXXRecordDecl(); | |||
11210 | if (!BaseRD) | |||
11211 | continue; | |||
11212 | ||||
11213 | auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); | |||
11214 | if (!BaseCtor.first) | |||
11215 | continue; | |||
11216 | ||||
11217 | MarkFunctionReferenced(CurrentLocation, BaseCtor.first); | |||
11218 | ExprResult Init = new (Context) CXXInheritedCtorInitExpr( | |||
11219 | InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); | |||
11220 | ||||
11221 | auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); | |||
11222 | Inits.push_back(new (Context) CXXCtorInitializer( | |||
11223 | Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, | |||
11224 | SourceLocation())); | |||
11225 | } | |||
11226 | } | |||
11227 | ||||
11228 | // We now proceed as if for a defaulted default constructor, with the relevant | |||
11229 | // initializers replaced. | |||
11230 | ||||
11231 | if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { | |||
11232 | Constructor->setInvalidDecl(); | |||
11233 | return; | |||
11234 | } | |||
11235 | ||||
11236 | Constructor->setBody(new (Context) CompoundStmt(InitLoc)); | |||
11237 | Constructor->markUsed(Context); | |||
11238 | ||||
11239 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
11240 | L->CompletedImplicitDefinition(Constructor); | |||
11241 | } | |||
11242 | ||||
11243 | DiagnoseUninitializedFields(*this, Constructor); | |||
11244 | } | |||
11245 | ||||
11246 | CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { | |||
11247 | // C++ [class.dtor]p2: | |||
11248 | // If a class has no user-declared destructor, a destructor is | |||
11249 | // declared implicitly. An implicitly-declared destructor is an | |||
11250 | // inline public member of its class. | |||
11251 | assert(ClassDecl->needsImplicitDestructor())((ClassDecl->needsImplicitDestructor()) ? static_cast<void > (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11251, __PRETTY_FUNCTION__)); | |||
11252 | ||||
11253 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); | |||
11254 | if (DSM.isAlreadyBeingDeclared()) | |||
11255 | return nullptr; | |||
11256 | ||||
11257 | // Create the actual destructor declaration. | |||
11258 | CanQualType ClassType | |||
11259 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
11260 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
11261 | DeclarationName Name | |||
11262 | = Context.DeclarationNames.getCXXDestructorName(ClassType); | |||
11263 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
11264 | CXXDestructorDecl *Destructor | |||
11265 | = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, | |||
11266 | QualType(), nullptr, /*isInline=*/true, | |||
11267 | /*isImplicitlyDeclared=*/true); | |||
11268 | Destructor->setAccess(AS_public); | |||
11269 | Destructor->setDefaulted(); | |||
11270 | ||||
11271 | if (getLangOpts().CUDA) { | |||
11272 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, | |||
11273 | Destructor, | |||
11274 | /* ConstRHS */ false, | |||
11275 | /* Diagnose */ false); | |||
11276 | } | |||
11277 | ||||
11278 | setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); | |||
11279 | ||||
11280 | // We don't need to use SpecialMemberIsTrivial here; triviality for | |||
11281 | // destructors is easy to compute. | |||
11282 | Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); | |||
11283 | Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || | |||
11284 | ClassDecl->hasTrivialDestructorForCall()); | |||
11285 | ||||
11286 | // Note that we have declared this destructor. | |||
11287 | ++getASTContext().NumImplicitDestructorsDeclared; | |||
11288 | ||||
11289 | Scope *S = getScopeForContext(ClassDecl); | |||
11290 | CheckImplicitSpecialMemberDeclaration(S, Destructor); | |||
11291 | ||||
11292 | // We can't check whether an implicit destructor is deleted before we complete | |||
11293 | // the definition of the class, because its validity depends on the alignment | |||
11294 | // of the class. We'll check this from ActOnFields once the class is complete. | |||
11295 | if (ClassDecl->isCompleteDefinition() && | |||
11296 | ShouldDeleteSpecialMember(Destructor, CXXDestructor)) | |||
11297 | SetDeclDeleted(Destructor, ClassLoc); | |||
11298 | ||||
11299 | // Introduce this destructor into its scope. | |||
11300 | if (S) | |||
11301 | PushOnScopeChains(Destructor, S, false); | |||
11302 | ClassDecl->addDecl(Destructor); | |||
11303 | ||||
11304 | return Destructor; | |||
11305 | } | |||
11306 | ||||
11307 | void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, | |||
11308 | CXXDestructorDecl *Destructor) { | |||
11309 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11312, __PRETTY_FUNCTION__)) | |||
11310 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11312, __PRETTY_FUNCTION__)) | |||
11311 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11312, __PRETTY_FUNCTION__)) | |||
11312 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11312, __PRETTY_FUNCTION__)); | |||
11313 | if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) | |||
11314 | return; | |||
11315 | ||||
11316 | CXXRecordDecl *ClassDecl = Destructor->getParent(); | |||
11317 | assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")((ClassDecl && "DefineImplicitDestructor - invalid destructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11317, __PRETTY_FUNCTION__)); | |||
11318 | ||||
11319 | SynthesizedFunctionScope Scope(*this, Destructor); | |||
11320 | ||||
11321 | // The exception specification is needed because we are defining the | |||
11322 | // function. | |||
11323 | ResolveExceptionSpec(CurrentLocation, | |||
11324 | Destructor->getType()->castAs<FunctionProtoType>()); | |||
11325 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
11326 | ||||
11327 | // Add a context note for diagnostics produced after this point. | |||
11328 | Scope.addContextNote(CurrentLocation); | |||
11329 | ||||
11330 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | |||
11331 | Destructor->getParent()); | |||
11332 | ||||
11333 | if (CheckDestructor(Destructor)) { | |||
11334 | Destructor->setInvalidDecl(); | |||
11335 | return; | |||
11336 | } | |||
11337 | ||||
11338 | SourceLocation Loc = Destructor->getEndLoc().isValid() | |||
11339 | ? Destructor->getEndLoc() | |||
11340 | : Destructor->getLocation(); | |||
11341 | Destructor->setBody(new (Context) CompoundStmt(Loc)); | |||
11342 | Destructor->markUsed(Context); | |||
11343 | ||||
11344 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
11345 | L->CompletedImplicitDefinition(Destructor); | |||
11346 | } | |||
11347 | } | |||
11348 | ||||
11349 | /// Perform any semantic analysis which needs to be delayed until all | |||
11350 | /// pending class member declarations have been parsed. | |||
11351 | void Sema::ActOnFinishCXXMemberDecls() { | |||
11352 | // If the context is an invalid C++ class, just suppress these checks. | |||
11353 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { | |||
11354 | if (Record->isInvalidDecl()) { | |||
11355 | DelayedOverridingExceptionSpecChecks.clear(); | |||
11356 | DelayedEquivalentExceptionSpecChecks.clear(); | |||
11357 | return; | |||
11358 | } | |||
11359 | checkForMultipleExportedDefaultConstructors(*this, Record); | |||
11360 | } | |||
11361 | } | |||
11362 | ||||
11363 | void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { | |||
11364 | referenceDLLExportedClassMethods(); | |||
11365 | } | |||
11366 | ||||
11367 | void Sema::referenceDLLExportedClassMethods() { | |||
11368 | if (!DelayedDllExportClasses.empty()) { | |||
11369 | // Calling ReferenceDllExportedMembers might cause the current function to | |||
11370 | // be called again, so use a local copy of DelayedDllExportClasses. | |||
11371 | SmallVector<CXXRecordDecl *, 4> WorkList; | |||
11372 | std::swap(DelayedDllExportClasses, WorkList); | |||
11373 | for (CXXRecordDecl *Class : WorkList) | |||
11374 | ReferenceDllExportedMembers(*this, Class); | |||
11375 | } | |||
11376 | } | |||
11377 | ||||
11378 | void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { | |||
11379 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11380, __PRETTY_FUNCTION__)) | |||
11380 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11380, __PRETTY_FUNCTION__)); | |||
11381 | ||||
11382 | if (Destructor->isDependentContext()) | |||
11383 | return; | |||
11384 | ||||
11385 | // C++11 [class.dtor]p3: | |||
11386 | // A declaration of a destructor that does not have an exception- | |||
11387 | // specification is implicitly considered to have the same exception- | |||
11388 | // specification as an implicit declaration. | |||
11389 | const FunctionProtoType *DtorType = Destructor->getType()-> | |||
11390 | getAs<FunctionProtoType>(); | |||
11391 | if (DtorType->hasExceptionSpec()) | |||
11392 | return; | |||
11393 | ||||
11394 | // Replace the destructor's type, building off the existing one. Fortunately, | |||
11395 | // the only thing of interest in the destructor type is its extended info. | |||
11396 | // The return and arguments are fixed. | |||
11397 | FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); | |||
11398 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
11399 | EPI.ExceptionSpec.SourceDecl = Destructor; | |||
11400 | Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); | |||
11401 | ||||
11402 | // FIXME: If the destructor has a body that could throw, and the newly created | |||
11403 | // spec doesn't allow exceptions, we should emit a warning, because this | |||
11404 | // change in behavior can break conforming C++03 programs at runtime. | |||
11405 | // However, we don't have a body or an exception specification yet, so it | |||
11406 | // needs to be done somewhere else. | |||
11407 | } | |||
11408 | ||||
11409 | namespace { | |||
11410 | /// An abstract base class for all helper classes used in building the | |||
11411 | // copy/move operators. These classes serve as factory functions and help us | |||
11412 | // avoid using the same Expr* in the AST twice. | |||
11413 | class ExprBuilder { | |||
11414 | ExprBuilder(const ExprBuilder&) = delete; | |||
11415 | ExprBuilder &operator=(const ExprBuilder&) = delete; | |||
11416 | ||||
11417 | protected: | |||
11418 | static Expr *assertNotNull(Expr *E) { | |||
11419 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11419, __PRETTY_FUNCTION__)); | |||
11420 | return E; | |||
11421 | } | |||
11422 | ||||
11423 | public: | |||
11424 | ExprBuilder() {} | |||
11425 | virtual ~ExprBuilder() {} | |||
11426 | ||||
11427 | virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; | |||
11428 | }; | |||
11429 | ||||
11430 | class RefBuilder: public ExprBuilder { | |||
11431 | VarDecl *Var; | |||
11432 | QualType VarType; | |||
11433 | ||||
11434 | public: | |||
11435 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11436 | return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); | |||
11437 | } | |||
11438 | ||||
11439 | RefBuilder(VarDecl *Var, QualType VarType) | |||
11440 | : Var(Var), VarType(VarType) {} | |||
11441 | }; | |||
11442 | ||||
11443 | class ThisBuilder: public ExprBuilder { | |||
11444 | public: | |||
11445 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11446 | return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); | |||
11447 | } | |||
11448 | }; | |||
11449 | ||||
11450 | class CastBuilder: public ExprBuilder { | |||
11451 | const ExprBuilder &Builder; | |||
11452 | QualType Type; | |||
11453 | ExprValueKind Kind; | |||
11454 | const CXXCastPath &Path; | |||
11455 | ||||
11456 | public: | |||
11457 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11458 | return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, | |||
11459 | CK_UncheckedDerivedToBase, Kind, | |||
11460 | &Path).get()); | |||
11461 | } | |||
11462 | ||||
11463 | CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, | |||
11464 | const CXXCastPath &Path) | |||
11465 | : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} | |||
11466 | }; | |||
11467 | ||||
11468 | class DerefBuilder: public ExprBuilder { | |||
11469 | const ExprBuilder &Builder; | |||
11470 | ||||
11471 | public: | |||
11472 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11473 | return assertNotNull( | |||
11474 | S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); | |||
11475 | } | |||
11476 | ||||
11477 | DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11478 | }; | |||
11479 | ||||
11480 | class MemberBuilder: public ExprBuilder { | |||
11481 | const ExprBuilder &Builder; | |||
11482 | QualType Type; | |||
11483 | CXXScopeSpec SS; | |||
11484 | bool IsArrow; | |||
11485 | LookupResult &MemberLookup; | |||
11486 | ||||
11487 | public: | |||
11488 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11489 | return assertNotNull(S.BuildMemberReferenceExpr( | |||
11490 | Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), | |||
11491 | nullptr, MemberLookup, nullptr, nullptr).get()); | |||
11492 | } | |||
11493 | ||||
11494 | MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, | |||
11495 | LookupResult &MemberLookup) | |||
11496 | : Builder(Builder), Type(Type), IsArrow(IsArrow), | |||
11497 | MemberLookup(MemberLookup) {} | |||
11498 | }; | |||
11499 | ||||
11500 | class MoveCastBuilder: public ExprBuilder { | |||
11501 | const ExprBuilder &Builder; | |||
11502 | ||||
11503 | public: | |||
11504 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11505 | return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); | |||
11506 | } | |||
11507 | ||||
11508 | MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11509 | }; | |||
11510 | ||||
11511 | class LvalueConvBuilder: public ExprBuilder { | |||
11512 | const ExprBuilder &Builder; | |||
11513 | ||||
11514 | public: | |||
11515 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11516 | return assertNotNull( | |||
11517 | S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); | |||
11518 | } | |||
11519 | ||||
11520 | LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11521 | }; | |||
11522 | ||||
11523 | class SubscriptBuilder: public ExprBuilder { | |||
11524 | const ExprBuilder &Base; | |||
11525 | const ExprBuilder &Index; | |||
11526 | ||||
11527 | public: | |||
11528 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11529 | return assertNotNull(S.CreateBuiltinArraySubscriptExpr( | |||
11530 | Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); | |||
11531 | } | |||
11532 | ||||
11533 | SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) | |||
11534 | : Base(Base), Index(Index) {} | |||
11535 | }; | |||
11536 | ||||
11537 | } // end anonymous namespace | |||
11538 | ||||
11539 | /// When generating a defaulted copy or move assignment operator, if a field | |||
11540 | /// should be copied with __builtin_memcpy rather than via explicit assignments, | |||
11541 | /// do so. This optimization only applies for arrays of scalars, and for arrays | |||
11542 | /// of class type where the selected copy/move-assignment operator is trivial. | |||
11543 | static StmtResult | |||
11544 | buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, | |||
11545 | const ExprBuilder &ToB, const ExprBuilder &FromB) { | |||
11546 | // Compute the size of the memory buffer to be copied. | |||
11547 | QualType SizeType = S.Context.getSizeType(); | |||
11548 | llvm::APInt Size(S.Context.getTypeSize(SizeType), | |||
11549 | S.Context.getTypeSizeInChars(T).getQuantity()); | |||
11550 | ||||
11551 | // Take the address of the field references for "from" and "to". We | |||
11552 | // directly construct UnaryOperators here because semantic analysis | |||
11553 | // does not permit us to take the address of an xvalue. | |||
11554 | Expr *From = FromB.build(S, Loc); | |||
11555 | From = new (S.Context) UnaryOperator(From, UO_AddrOf, | |||
11556 | S.Context.getPointerType(From->getType()), | |||
11557 | VK_RValue, OK_Ordinary, Loc, false); | |||
11558 | Expr *To = ToB.build(S, Loc); | |||
11559 | To = new (S.Context) UnaryOperator(To, UO_AddrOf, | |||
11560 | S.Context.getPointerType(To->getType()), | |||
11561 | VK_RValue, OK_Ordinary, Loc, false); | |||
11562 | ||||
11563 | const Type *E = T->getBaseElementTypeUnsafe(); | |||
11564 | bool NeedsCollectableMemCpy = | |||
11565 | E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); | |||
11566 | ||||
11567 | // Create a reference to the __builtin_objc_memmove_collectable function | |||
11568 | StringRef MemCpyName = NeedsCollectableMemCpy ? | |||
11569 | "__builtin_objc_memmove_collectable" : | |||
11570 | "__builtin_memcpy"; | |||
11571 | LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, | |||
11572 | Sema::LookupOrdinaryName); | |||
11573 | S.LookupName(R, S.TUScope, true); | |||
11574 | ||||
11575 | FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); | |||
11576 | if (!MemCpy) | |||
11577 | // Something went horribly wrong earlier, and we will have complained | |||
11578 | // about it. | |||
11579 | return StmtError(); | |||
11580 | ||||
11581 | ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, | |||
11582 | VK_RValue, Loc, nullptr); | |||
11583 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11583, __PRETTY_FUNCTION__)); | |||
11584 | ||||
11585 | Expr *CallArgs[] = { | |||
11586 | To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) | |||
11587 | }; | |||
11588 | ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), | |||
11589 | Loc, CallArgs, Loc); | |||
11590 | ||||
11591 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11591, __PRETTY_FUNCTION__)); | |||
11592 | return Call.getAs<Stmt>(); | |||
11593 | } | |||
11594 | ||||
11595 | /// Builds a statement that copies/moves the given entity from \p From to | |||
11596 | /// \c To. | |||
11597 | /// | |||
11598 | /// This routine is used to copy/move the members of a class with an | |||
11599 | /// implicitly-declared copy/move assignment operator. When the entities being | |||
11600 | /// copied are arrays, this routine builds for loops to copy them. | |||
11601 | /// | |||
11602 | /// \param S The Sema object used for type-checking. | |||
11603 | /// | |||
11604 | /// \param Loc The location where the implicit copy/move is being generated. | |||
11605 | /// | |||
11606 | /// \param T The type of the expressions being copied/moved. Both expressions | |||
11607 | /// must have this type. | |||
11608 | /// | |||
11609 | /// \param To The expression we are copying/moving to. | |||
11610 | /// | |||
11611 | /// \param From The expression we are copying/moving from. | |||
11612 | /// | |||
11613 | /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. | |||
11614 | /// Otherwise, it's a non-static member subobject. | |||
11615 | /// | |||
11616 | /// \param Copying Whether we're copying or moving. | |||
11617 | /// | |||
11618 | /// \param Depth Internal parameter recording the depth of the recursion. | |||
11619 | /// | |||
11620 | /// \returns A statement or a loop that copies the expressions, or StmtResult(0) | |||
11621 | /// if a memcpy should be used instead. | |||
11622 | static StmtResult | |||
11623 | buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, | |||
11624 | const ExprBuilder &To, const ExprBuilder &From, | |||
11625 | bool CopyingBaseSubobject, bool Copying, | |||
11626 | unsigned Depth = 0) { | |||
11627 | // C++11 [class.copy]p28: | |||
11628 | // Each subobject is assigned in the manner appropriate to its type: | |||
11629 | // | |||
11630 | // - if the subobject is of class type, as if by a call to operator= with | |||
11631 | // the subobject as the object expression and the corresponding | |||
11632 | // subobject of x as a single function argument (as if by explicit | |||
11633 | // qualification; that is, ignoring any possible virtual overriding | |||
11634 | // functions in more derived classes); | |||
11635 | // | |||
11636 | // C++03 [class.copy]p13: | |||
11637 | // - if the subobject is of class type, the copy assignment operator for | |||
11638 | // the class is used (as if by explicit qualification; that is, | |||
11639 | // ignoring any possible virtual overriding functions in more derived | |||
11640 | // classes); | |||
11641 | if (const RecordType *RecordTy = T->getAs<RecordType>()) { | |||
11642 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
11643 | ||||
11644 | // Look for operator=. | |||
11645 | DeclarationName Name | |||
11646 | = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
11647 | LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); | |||
11648 | S.LookupQualifiedName(OpLookup, ClassDecl, false); | |||
11649 | ||||
11650 | // Prior to C++11, filter out any result that isn't a copy/move-assignment | |||
11651 | // operator. | |||
11652 | if (!S.getLangOpts().CPlusPlus11) { | |||
11653 | LookupResult::Filter F = OpLookup.makeFilter(); | |||
11654 | while (F.hasNext()) { | |||
11655 | NamedDecl *D = F.next(); | |||
11656 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) | |||
11657 | if (Method->isCopyAssignmentOperator() || | |||
11658 | (!Copying && Method->isMoveAssignmentOperator())) | |||
11659 | continue; | |||
11660 | ||||
11661 | F.erase(); | |||
11662 | } | |||
11663 | F.done(); | |||
11664 | } | |||
11665 | ||||
11666 | // Suppress the protected check (C++ [class.protected]) for each of the | |||
11667 | // assignment operators we found. This strange dance is required when | |||
11668 | // we're assigning via a base classes's copy-assignment operator. To | |||
11669 | // ensure that we're getting the right base class subobject (without | |||
11670 | // ambiguities), we need to cast "this" to that subobject type; to | |||
11671 | // ensure that we don't go through the virtual call mechanism, we need | |||
11672 | // to qualify the operator= name with the base class (see below). However, | |||
11673 | // this means that if the base class has a protected copy assignment | |||
11674 | // operator, the protected member access check will fail. So, we | |||
11675 | // rewrite "protected" access to "public" access in this case, since we | |||
11676 | // know by construction that we're calling from a derived class. | |||
11677 | if (CopyingBaseSubobject) { | |||
11678 | for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); | |||
11679 | L != LEnd; ++L) { | |||
11680 | if (L.getAccess() == AS_protected) | |||
11681 | L.setAccess(AS_public); | |||
11682 | } | |||
11683 | } | |||
11684 | ||||
11685 | // Create the nested-name-specifier that will be used to qualify the | |||
11686 | // reference to operator=; this is required to suppress the virtual | |||
11687 | // call mechanism. | |||
11688 | CXXScopeSpec SS; | |||
11689 | const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); | |||
11690 | SS.MakeTrivial(S.Context, | |||
11691 | NestedNameSpecifier::Create(S.Context, nullptr, false, | |||
11692 | CanonicalT), | |||
11693 | Loc); | |||
11694 | ||||
11695 | // Create the reference to operator=. | |||
11696 | ExprResult OpEqualRef | |||
11697 | = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, | |||
11698 | SS, /*TemplateKWLoc=*/SourceLocation(), | |||
11699 | /*FirstQualifierInScope=*/nullptr, | |||
11700 | OpLookup, | |||
11701 | /*TemplateArgs=*/nullptr, /*S*/nullptr, | |||
11702 | /*SuppressQualifierCheck=*/true); | |||
11703 | if (OpEqualRef.isInvalid()) | |||
11704 | return StmtError(); | |||
11705 | ||||
11706 | // Build the call to the assignment operator. | |||
11707 | ||||
11708 | Expr *FromInst = From.build(S, Loc); | |||
11709 | ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, | |||
11710 | OpEqualRef.getAs<Expr>(), | |||
11711 | Loc, FromInst, Loc); | |||
11712 | if (Call.isInvalid()) | |||
11713 | return StmtError(); | |||
11714 | ||||
11715 | // If we built a call to a trivial 'operator=' while copying an array, | |||
11716 | // bail out. We'll replace the whole shebang with a memcpy. | |||
11717 | CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); | |||
11718 | if (CE && CE->getMethodDecl()->isTrivial() && Depth) | |||
11719 | return StmtResult((Stmt*)nullptr); | |||
11720 | ||||
11721 | // Convert to an expression-statement, and clean up any produced | |||
11722 | // temporaries. | |||
11723 | return S.ActOnExprStmt(Call); | |||
11724 | } | |||
11725 | ||||
11726 | // - if the subobject is of scalar type, the built-in assignment | |||
11727 | // operator is used. | |||
11728 | const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); | |||
11729 | if (!ArrayTy) { | |||
11730 | ExprResult Assignment = S.CreateBuiltinBinOp( | |||
11731 | Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); | |||
11732 | if (Assignment.isInvalid()) | |||
11733 | return StmtError(); | |||
11734 | return S.ActOnExprStmt(Assignment); | |||
11735 | } | |||
11736 | ||||
11737 | // - if the subobject is an array, each element is assigned, in the | |||
11738 | // manner appropriate to the element type; | |||
11739 | ||||
11740 | // Construct a loop over the array bounds, e.g., | |||
11741 | // | |||
11742 | // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) | |||
11743 | // | |||
11744 | // that will copy each of the array elements. | |||
11745 | QualType SizeType = S.Context.getSizeType(); | |||
11746 | ||||
11747 | // Create the iteration variable. | |||
11748 | IdentifierInfo *IterationVarName = nullptr; | |||
11749 | { | |||
11750 | SmallString<8> Str; | |||
11751 | llvm::raw_svector_ostream OS(Str); | |||
11752 | OS << "__i" << Depth; | |||
11753 | IterationVarName = &S.Context.Idents.get(OS.str()); | |||
11754 | } | |||
11755 | VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, | |||
11756 | IterationVarName, SizeType, | |||
11757 | S.Context.getTrivialTypeSourceInfo(SizeType, Loc), | |||
11758 | SC_None); | |||
11759 | ||||
11760 | // Initialize the iteration variable to zero. | |||
11761 | llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); | |||
11762 | IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); | |||
11763 | ||||
11764 | // Creates a reference to the iteration variable. | |||
11765 | RefBuilder IterationVarRef(IterationVar, SizeType); | |||
11766 | LvalueConvBuilder IterationVarRefRVal(IterationVarRef); | |||
11767 | ||||
11768 | // Create the DeclStmt that holds the iteration variable. | |||
11769 | Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); | |||
11770 | ||||
11771 | // Subscript the "from" and "to" expressions with the iteration variable. | |||
11772 | SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); | |||
11773 | MoveCastBuilder FromIndexMove(FromIndexCopy); | |||
11774 | const ExprBuilder *FromIndex; | |||
11775 | if (Copying) | |||
11776 | FromIndex = &FromIndexCopy; | |||
11777 | else | |||
11778 | FromIndex = &FromIndexMove; | |||
11779 | ||||
11780 | SubscriptBuilder ToIndex(To, IterationVarRefRVal); | |||
11781 | ||||
11782 | // Build the copy/move for an individual element of the array. | |||
11783 | StmtResult Copy = | |||
11784 | buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), | |||
11785 | ToIndex, *FromIndex, CopyingBaseSubobject, | |||
11786 | Copying, Depth + 1); | |||
11787 | // Bail out if copying fails or if we determined that we should use memcpy. | |||
11788 | if (Copy.isInvalid() || !Copy.get()) | |||
11789 | return Copy; | |||
11790 | ||||
11791 | // Create the comparison against the array bound. | |||
11792 | llvm::APInt Upper | |||
11793 | = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); | |||
11794 | Expr *Comparison | |||
11795 | = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), | |||
11796 | IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), | |||
11797 | BO_NE, S.Context.BoolTy, | |||
11798 | VK_RValue, OK_Ordinary, Loc, FPOptions()); | |||
11799 | ||||
11800 | // Create the pre-increment of the iteration variable. We can determine | |||
11801 | // whether the increment will overflow based on the value of the array | |||
11802 | // bound. | |||
11803 | Expr *Increment = new (S.Context) | |||
11804 | UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, | |||
11805 | VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); | |||
11806 | ||||
11807 | // Construct the loop that copies all elements of this array. | |||
11808 | return S.ActOnForStmt( | |||
11809 | Loc, Loc, InitStmt, | |||
11810 | S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), | |||
11811 | S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); | |||
11812 | } | |||
11813 | ||||
11814 | static StmtResult | |||
11815 | buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, | |||
11816 | const ExprBuilder &To, const ExprBuilder &From, | |||
11817 | bool CopyingBaseSubobject, bool Copying) { | |||
11818 | // Maybe we should use a memcpy? | |||
11819 | if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && | |||
11820 | T.isTriviallyCopyableType(S.Context)) | |||
11821 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | |||
11822 | ||||
11823 | StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, | |||
11824 | CopyingBaseSubobject, | |||
11825 | Copying, 0)); | |||
11826 | ||||
11827 | // If we ended up picking a trivial assignment operator for an array of a | |||
11828 | // non-trivially-copyable class type, just emit a memcpy. | |||
11829 | if (!Result.isInvalid() && !Result.get()) | |||
11830 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | |||
11831 | ||||
11832 | return Result; | |||
11833 | } | |||
11834 | ||||
11835 | CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { | |||
11836 | // Note: The following rules are largely analoguous to the copy | |||
11837 | // constructor rules. Note that virtual bases are not taken into account | |||
11838 | // for determining the argument type of the operator. Note also that | |||
11839 | // operators taking an object instead of a reference are allowed. | |||
11840 | assert(ClassDecl->needsImplicitCopyAssignment())((ClassDecl->needsImplicitCopyAssignment()) ? static_cast< void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11840, __PRETTY_FUNCTION__)); | |||
11841 | ||||
11842 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); | |||
11843 | if (DSM.isAlreadyBeingDeclared()) | |||
11844 | return nullptr; | |||
11845 | ||||
11846 | QualType ArgType = Context.getTypeDeclType(ClassDecl); | |||
11847 | if (Context.getLangOpts().OpenCLCPlusPlus) | |||
11848 | ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); | |||
11849 | QualType RetType = Context.getLValueReferenceType(ArgType); | |||
11850 | bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); | |||
11851 | if (Const) | |||
11852 | ArgType = ArgType.withConst(); | |||
11853 | ||||
11854 | ArgType = Context.getLValueReferenceType(ArgType); | |||
11855 | ||||
11856 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
11857 | CXXCopyAssignment, | |||
11858 | Const); | |||
11859 | ||||
11860 | // An implicitly-declared copy assignment operator is an inline public | |||
11861 | // member of its class. | |||
11862 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
11863 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
11864 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
11865 | CXXMethodDecl *CopyAssignment = | |||
11866 | CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), | |||
11867 | /*TInfo=*/nullptr, /*StorageClass=*/SC_None, | |||
11868 | /*isInline=*/true, Constexpr, SourceLocation()); | |||
11869 | CopyAssignment->setAccess(AS_public); | |||
11870 | CopyAssignment->setDefaulted(); | |||
11871 | CopyAssignment->setImplicit(); | |||
11872 | ||||
11873 | if (getLangOpts().CUDA) { | |||
11874 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, | |||
11875 | CopyAssignment, | |||
11876 | /* ConstRHS */ Const, | |||
11877 | /* Diagnose */ false); | |||
11878 | } | |||
11879 | ||||
11880 | setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); | |||
11881 | ||||
11882 | // Add the parameter to the operator. | |||
11883 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, | |||
11884 | ClassLoc, ClassLoc, | |||
11885 | /*Id=*/nullptr, ArgType, | |||
11886 | /*TInfo=*/nullptr, SC_None, | |||
11887 | nullptr); | |||
11888 | CopyAssignment->setParams(FromParam); | |||
11889 | ||||
11890 | CopyAssignment->setTrivial( | |||
11891 | ClassDecl->needsOverloadResolutionForCopyAssignment() | |||
11892 | ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) | |||
11893 | : ClassDecl->hasTrivialCopyAssignment()); | |||
11894 | ||||
11895 | // Note that we have added this copy-assignment operator. | |||
11896 | ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; | |||
11897 | ||||
11898 | Scope *S = getScopeForContext(ClassDecl); | |||
11899 | CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); | |||
11900 | ||||
11901 | if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) | |||
11902 | SetDeclDeleted(CopyAssignment, ClassLoc); | |||
11903 | ||||
11904 | if (S) | |||
11905 | PushOnScopeChains(CopyAssignment, S, false); | |||
11906 | ClassDecl->addDecl(CopyAssignment); | |||
11907 | ||||
11908 | return CopyAssignment; | |||
11909 | } | |||
11910 | ||||
11911 | /// Diagnose an implicit copy operation for a class which is odr-used, but | |||
11912 | /// which is deprecated because the class has a user-declared copy constructor, | |||
11913 | /// copy assignment operator, or destructor. | |||
11914 | static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { | |||
11915 | assert(CopyOp->isImplicit())((CopyOp->isImplicit()) ? static_cast<void> (0) : __assert_fail ("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11915, __PRETTY_FUNCTION__)); | |||
11916 | ||||
11917 | CXXRecordDecl *RD = CopyOp->getParent(); | |||
11918 | CXXMethodDecl *UserDeclaredOperation = nullptr; | |||
11919 | ||||
11920 | // In Microsoft mode, assignment operations don't affect constructors and | |||
11921 | // vice versa. | |||
11922 | if (RD->hasUserDeclaredDestructor()) { | |||
11923 | UserDeclaredOperation = RD->getDestructor(); | |||
11924 | } else if (!isa<CXXConstructorDecl>(CopyOp) && | |||
11925 | RD->hasUserDeclaredCopyConstructor() && | |||
11926 | !S.getLangOpts().MSVCCompat) { | |||
11927 | // Find any user-declared copy constructor. | |||
11928 | for (auto *I : RD->ctors()) { | |||
11929 | if (I->isCopyConstructor()) { | |||
11930 | UserDeclaredOperation = I; | |||
11931 | break; | |||
11932 | } | |||
11933 | } | |||
11934 | assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11934, __PRETTY_FUNCTION__)); | |||
11935 | } else if (isa<CXXConstructorDecl>(CopyOp) && | |||
11936 | RD->hasUserDeclaredCopyAssignment() && | |||
11937 | !S.getLangOpts().MSVCCompat) { | |||
11938 | // Find any user-declared move assignment operator. | |||
11939 | for (auto *I : RD->methods()) { | |||
11940 | if (I->isCopyAssignmentOperator()) { | |||
11941 | UserDeclaredOperation = I; | |||
11942 | break; | |||
11943 | } | |||
11944 | } | |||
11945 | assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11945, __PRETTY_FUNCTION__)); | |||
11946 | } | |||
11947 | ||||
11948 | if (UserDeclaredOperation) { | |||
11949 | S.Diag(UserDeclaredOperation->getLocation(), | |||
11950 | diag::warn_deprecated_copy_operation) | |||
11951 | << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) | |||
11952 | << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); | |||
11953 | } | |||
11954 | } | |||
11955 | ||||
11956 | void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, | |||
11957 | CXXMethodDecl *CopyAssignOperator) { | |||
11958 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11963, __PRETTY_FUNCTION__)) | |||
11959 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11963, __PRETTY_FUNCTION__)) | |||
11960 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11963, __PRETTY_FUNCTION__)) | |||
11961 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11963, __PRETTY_FUNCTION__)) | |||
11962 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11963, __PRETTY_FUNCTION__)) | |||
11963 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11963, __PRETTY_FUNCTION__)); | |||
11964 | if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) | |||
11965 | return; | |||
11966 | ||||
11967 | CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); | |||
11968 | if (ClassDecl->isInvalidDecl()) { | |||
11969 | CopyAssignOperator->setInvalidDecl(); | |||
11970 | return; | |||
11971 | } | |||
11972 | ||||
11973 | SynthesizedFunctionScope Scope(*this, CopyAssignOperator); | |||
11974 | ||||
11975 | // The exception specification is needed because we are defining the | |||
11976 | // function. | |||
11977 | ResolveExceptionSpec(CurrentLocation, | |||
11978 | CopyAssignOperator->getType()->castAs<FunctionProtoType>()); | |||
11979 | ||||
11980 | // Add a context note for diagnostics produced after this point. | |||
11981 | Scope.addContextNote(CurrentLocation); | |||
11982 | ||||
11983 | // C++11 [class.copy]p18: | |||
11984 | // The [definition of an implicitly declared copy assignment operator] is | |||
11985 | // deprecated if the class has a user-declared copy constructor or a | |||
11986 | // user-declared destructor. | |||
11987 | if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) | |||
11988 | diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); | |||
11989 | ||||
11990 | // C++0x [class.copy]p30: | |||
11991 | // The implicitly-defined or explicitly-defaulted copy assignment operator | |||
11992 | // for a non-union class X performs memberwise copy assignment of its | |||
11993 | // subobjects. The direct base classes of X are assigned first, in the | |||
11994 | // order of their declaration in the base-specifier-list, and then the | |||
11995 | // immediate non-static data members of X are assigned, in the order in | |||
11996 | // which they were declared in the class definition. | |||
11997 | ||||
11998 | // The statements that form the synthesized function body. | |||
11999 | SmallVector<Stmt*, 8> Statements; | |||
12000 | ||||
12001 | // The parameter for the "other" object, which we are copying from. | |||
12002 | ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); | |||
12003 | Qualifiers OtherQuals = Other->getType().getQualifiers(); | |||
12004 | QualType OtherRefType = Other->getType(); | |||
12005 | if (const LValueReferenceType *OtherRef | |||
12006 | = OtherRefType->getAs<LValueReferenceType>()) { | |||
12007 | OtherRefType = OtherRef->getPointeeType(); | |||
12008 | OtherQuals = OtherRefType.getQualifiers(); | |||
12009 | } | |||
12010 | ||||
12011 | // Our location for everything implicitly-generated. | |||
12012 | SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() | |||
12013 | ? CopyAssignOperator->getEndLoc() | |||
12014 | : CopyAssignOperator->getLocation(); | |||
12015 | ||||
12016 | // Builds a DeclRefExpr for the "other" object. | |||
12017 | RefBuilder OtherRef(Other, OtherRefType); | |||
12018 | ||||
12019 | // Builds the "this" pointer. | |||
12020 | ThisBuilder This; | |||
12021 | ||||
12022 | // Assign base classes. | |||
12023 | bool Invalid = false; | |||
12024 | for (auto &Base : ClassDecl->bases()) { | |||
12025 | // Form the assignment: | |||
12026 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); | |||
12027 | QualType BaseType = Base.getType().getUnqualifiedType(); | |||
12028 | if (!BaseType->isRecordType()) { | |||
12029 | Invalid = true; | |||
12030 | continue; | |||
12031 | } | |||
12032 | ||||
12033 | CXXCastPath BasePath; | |||
12034 | BasePath.push_back(&Base); | |||
12035 | ||||
12036 | // Construct the "from" expression, which is an implicit cast to the | |||
12037 | // appropriately-qualified base type. | |||
12038 | CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), | |||
12039 | VK_LValue, BasePath); | |||
12040 | ||||
12041 | // Dereference "this". | |||
12042 | DerefBuilder DerefThis(This); | |||
12043 | CastBuilder To(DerefThis, | |||
12044 | Context.getQualifiedType( | |||
12045 | BaseType, CopyAssignOperator->getMethodQualifiers()), | |||
12046 | VK_LValue, BasePath); | |||
12047 | ||||
12048 | // Build the copy. | |||
12049 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, | |||
12050 | To, From, | |||
12051 | /*CopyingBaseSubobject=*/true, | |||
12052 | /*Copying=*/true); | |||
12053 | if (Copy.isInvalid()) { | |||
12054 | CopyAssignOperator->setInvalidDecl(); | |||
12055 | return; | |||
12056 | } | |||
12057 | ||||
12058 | // Success! Record the copy. | |||
12059 | Statements.push_back(Copy.getAs<Expr>()); | |||
12060 | } | |||
12061 | ||||
12062 | // Assign non-static members. | |||
12063 | for (auto *Field : ClassDecl->fields()) { | |||
12064 | // FIXME: We should form some kind of AST representation for the implied | |||
12065 | // memcpy in a union copy operation. | |||
12066 | if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) | |||
12067 | continue; | |||
12068 | ||||
12069 | if (Field->isInvalidDecl()) { | |||
12070 | Invalid = true; | |||
12071 | continue; | |||
12072 | } | |||
12073 | ||||
12074 | // Check for members of reference type; we can't copy those. | |||
12075 | if (Field->getType()->isReferenceType()) { | |||
12076 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
12077 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); | |||
12078 | Diag(Field->getLocation(), diag::note_declared_at); | |||
12079 | Invalid = true; | |||
12080 | continue; | |||
12081 | } | |||
12082 | ||||
12083 | // Check for members of const-qualified, non-class type. | |||
12084 | QualType BaseType = Context.getBaseElementType(Field->getType()); | |||
12085 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { | |||
12086 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
12087 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); | |||
12088 | Diag(Field->getLocation(), diag::note_declared_at); | |||
12089 | Invalid = true; | |||
12090 | continue; | |||
12091 | } | |||
12092 | ||||
12093 | // Suppress assigning zero-width bitfields. | |||
12094 | if (Field->isZeroLengthBitField(Context)) | |||
12095 | continue; | |||
12096 | ||||
12097 | QualType FieldType = Field->getType().getNonReferenceType(); | |||
12098 | if (FieldType->isIncompleteArrayType()) { | |||
12099 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12100, __PRETTY_FUNCTION__)) | |||
12100 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12100, __PRETTY_FUNCTION__)); | |||
12101 | continue; | |||
12102 | } | |||
12103 | ||||
12104 | // Build references to the field in the object we're copying from and to. | |||
12105 | CXXScopeSpec SS; // Intentionally empty | |||
12106 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, | |||
12107 | LookupMemberName); | |||
12108 | MemberLookup.addDecl(Field); | |||
12109 | MemberLookup.resolveKind(); | |||
12110 | ||||
12111 | MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); | |||
12112 | ||||
12113 | MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); | |||
12114 | ||||
12115 | // Build the copy of this field. | |||
12116 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, | |||
12117 | To, From, | |||
12118 | /*CopyingBaseSubobject=*/false, | |||
12119 | /*Copying=*/true); | |||
12120 | if (Copy.isInvalid()) { | |||
12121 | CopyAssignOperator->setInvalidDecl(); | |||
12122 | return; | |||
12123 | } | |||
12124 | ||||
12125 | // Success! Record the copy. | |||
12126 | Statements.push_back(Copy.getAs<Stmt>()); | |||
12127 | } | |||
12128 | ||||
12129 | if (!Invalid) { | |||
12130 | // Add a "return *this;" | |||
12131 | ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); | |||
12132 | ||||
12133 | StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); | |||
12134 | if (Return.isInvalid()) | |||
12135 | Invalid = true; | |||
12136 | else | |||
12137 | Statements.push_back(Return.getAs<Stmt>()); | |||
12138 | } | |||
12139 | ||||
12140 | if (Invalid) { | |||
12141 | CopyAssignOperator->setInvalidDecl(); | |||
12142 | return; | |||
12143 | } | |||
12144 | ||||
12145 | StmtResult Body; | |||
12146 | { | |||
12147 | CompoundScopeRAII CompoundScope(*this); | |||
12148 | Body = ActOnCompoundStmt(Loc, Loc, Statements, | |||
12149 | /*isStmtExpr=*/false); | |||
12150 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12150, __PRETTY_FUNCTION__)); | |||
12151 | } | |||
12152 | CopyAssignOperator->setBody(Body.getAs<Stmt>()); | |||
12153 | CopyAssignOperator->markUsed(Context); | |||
12154 | ||||
12155 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12156 | L->CompletedImplicitDefinition(CopyAssignOperator); | |||
12157 | } | |||
12158 | } | |||
12159 | ||||
12160 | CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { | |||
12161 | assert(ClassDecl->needsImplicitMoveAssignment())((ClassDecl->needsImplicitMoveAssignment()) ? static_cast< void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12161, __PRETTY_FUNCTION__)); | |||
12162 | ||||
12163 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); | |||
12164 | if (DSM.isAlreadyBeingDeclared()) | |||
12165 | return nullptr; | |||
12166 | ||||
12167 | // Note: The following rules are largely analoguous to the move | |||
12168 | // constructor rules. | |||
12169 | ||||
12170 | QualType ArgType = Context.getTypeDeclType(ClassDecl); | |||
12171 | if (Context.getLangOpts().OpenCLCPlusPlus) | |||
12172 | ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); | |||
12173 | QualType RetType = Context.getLValueReferenceType(ArgType); | |||
12174 | ArgType = Context.getRValueReferenceType(ArgType); | |||
12175 | ||||
12176 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
12177 | CXXMoveAssignment, | |||
12178 | false); | |||
12179 | ||||
12180 | // An implicitly-declared move assignment operator is an inline public | |||
12181 | // member of its class. | |||
12182 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
12183 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
12184 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
12185 | CXXMethodDecl *MoveAssignment = | |||
12186 | CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), | |||
12187 | /*TInfo=*/nullptr, /*StorageClass=*/SC_None, | |||
12188 | /*isInline=*/true, Constexpr, SourceLocation()); | |||
12189 | MoveAssignment->setAccess(AS_public); | |||
12190 | MoveAssignment->setDefaulted(); | |||
12191 | MoveAssignment->setImplicit(); | |||
12192 | ||||
12193 | if (getLangOpts().CUDA) { | |||
12194 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, | |||
12195 | MoveAssignment, | |||
12196 | /* ConstRHS */ false, | |||
12197 | /* Diagnose */ false); | |||
12198 | } | |||
12199 | ||||
12200 | // Build an exception specification pointing back at this member. | |||
12201 | FunctionProtoType::ExtProtoInfo EPI = | |||
12202 | getImplicitMethodEPI(*this, MoveAssignment); | |||
12203 | MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); | |||
12204 | ||||
12205 | // Add the parameter to the operator. | |||
12206 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, | |||
12207 | ClassLoc, ClassLoc, | |||
12208 | /*Id=*/nullptr, ArgType, | |||
12209 | /*TInfo=*/nullptr, SC_None, | |||
12210 | nullptr); | |||
12211 | MoveAssignment->setParams(FromParam); | |||
12212 | ||||
12213 | MoveAssignment->setTrivial( | |||
12214 | ClassDecl->needsOverloadResolutionForMoveAssignment() | |||
12215 | ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) | |||
12216 | : ClassDecl->hasTrivialMoveAssignment()); | |||
12217 | ||||
12218 | // Note that we have added this copy-assignment operator. | |||
12219 | ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; | |||
12220 | ||||
12221 | Scope *S = getScopeForContext(ClassDecl); | |||
12222 | CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); | |||
12223 | ||||
12224 | if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { | |||
12225 | ClassDecl->setImplicitMoveAssignmentIsDeleted(); | |||
12226 | SetDeclDeleted(MoveAssignment, ClassLoc); | |||
12227 | } | |||
12228 | ||||
12229 | if (S) | |||
12230 | PushOnScopeChains(MoveAssignment, S, false); | |||
12231 | ClassDecl->addDecl(MoveAssignment); | |||
12232 | ||||
12233 | return MoveAssignment; | |||
12234 | } | |||
12235 | ||||
12236 | /// Check if we're implicitly defining a move assignment operator for a class | |||
12237 | /// with virtual bases. Such a move assignment might move-assign the virtual | |||
12238 | /// base multiple times. | |||
12239 | static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, | |||
12240 | SourceLocation CurrentLocation) { | |||
12241 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12241, __PRETTY_FUNCTION__)); | |||
12242 | ||||
12243 | // Only a virtual base could get implicitly move-assigned multiple times. | |||
12244 | // Only a non-trivial move assignment can observe this. We only want to | |||
12245 | // diagnose if we implicitly define an assignment operator that assigns | |||
12246 | // two base classes, both of which move-assign the same virtual base. | |||
12247 | if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || | |||
12248 | Class->getNumBases() < 2) | |||
12249 | return; | |||
12250 | ||||
12251 | llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; | |||
12252 | typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; | |||
12253 | VBaseMap VBases; | |||
12254 | ||||
12255 | for (auto &BI : Class->bases()) { | |||
12256 | Worklist.push_back(&BI); | |||
12257 | while (!Worklist.empty()) { | |||
12258 | CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); | |||
12259 | CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); | |||
12260 | ||||
12261 | // If the base has no non-trivial move assignment operators, | |||
12262 | // we don't care about moves from it. | |||
12263 | if (!Base->hasNonTrivialMoveAssignment()) | |||
12264 | continue; | |||
12265 | ||||
12266 | // If there's nothing virtual here, skip it. | |||
12267 | if (!BaseSpec->isVirtual() && !Base->getNumVBases()) | |||
12268 | continue; | |||
12269 | ||||
12270 | // If we're not actually going to call a move assignment for this base, | |||
12271 | // or the selected move assignment is trivial, skip it. | |||
12272 | Sema::SpecialMemberOverloadResult SMOR = | |||
12273 | S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, | |||
12274 | /*ConstArg*/false, /*VolatileArg*/false, | |||
12275 | /*RValueThis*/true, /*ConstThis*/false, | |||
12276 | /*VolatileThis*/false); | |||
12277 | if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || | |||
12278 | !SMOR.getMethod()->isMoveAssignmentOperator()) | |||
12279 | continue; | |||
12280 | ||||
12281 | if (BaseSpec->isVirtual()) { | |||
12282 | // We're going to move-assign this virtual base, and its move | |||
12283 | // assignment operator is not trivial. If this can happen for | |||
12284 | // multiple distinct direct bases of Class, diagnose it. (If it | |||
12285 | // only happens in one base, we'll diagnose it when synthesizing | |||
12286 | // that base class's move assignment operator.) | |||
12287 | CXXBaseSpecifier *&Existing = | |||
12288 | VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) | |||
12289 | .first->second; | |||
12290 | if (Existing && Existing != &BI) { | |||
12291 | S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) | |||
12292 | << Class << Base; | |||
12293 | S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) | |||
12294 | << (Base->getCanonicalDecl() == | |||
12295 | Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) | |||
12296 | << Base << Existing->getType() << Existing->getSourceRange(); | |||
12297 | S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) | |||
12298 | << (Base->getCanonicalDecl() == | |||
12299 | BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) | |||
12300 | << Base << BI.getType() << BaseSpec->getSourceRange(); | |||
12301 | ||||
12302 | // Only diagnose each vbase once. | |||
12303 | Existing = nullptr; | |||
12304 | } | |||
12305 | } else { | |||
12306 | // Only walk over bases that have defaulted move assignment operators. | |||
12307 | // We assume that any user-provided move assignment operator handles | |||
12308 | // the multiple-moves-of-vbase case itself somehow. | |||
12309 | if (!SMOR.getMethod()->isDefaulted()) | |||
12310 | continue; | |||
12311 | ||||
12312 | // We're going to move the base classes of Base. Add them to the list. | |||
12313 | for (auto &BI : Base->bases()) | |||
12314 | Worklist.push_back(&BI); | |||
12315 | } | |||
12316 | } | |||
12317 | } | |||
12318 | } | |||
12319 | ||||
12320 | void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, | |||
12321 | CXXMethodDecl *MoveAssignOperator) { | |||
12322 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12327, __PRETTY_FUNCTION__)) | |||
12323 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12327, __PRETTY_FUNCTION__)) | |||
12324 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12327, __PRETTY_FUNCTION__)) | |||
12325 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12327, __PRETTY_FUNCTION__)) | |||
12326 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12327, __PRETTY_FUNCTION__)) | |||
12327 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12327, __PRETTY_FUNCTION__)); | |||
12328 | if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) | |||
12329 | return; | |||
12330 | ||||
12331 | CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); | |||
12332 | if (ClassDecl->isInvalidDecl()) { | |||
12333 | MoveAssignOperator->setInvalidDecl(); | |||
12334 | return; | |||
12335 | } | |||
12336 | ||||
12337 | // C++0x [class.copy]p28: | |||
12338 | // The implicitly-defined or move assignment operator for a non-union class | |||
12339 | // X performs memberwise move assignment of its subobjects. The direct base | |||
12340 | // classes of X are assigned first, in the order of their declaration in the | |||
12341 | // base-specifier-list, and then the immediate non-static data members of X | |||
12342 | // are assigned, in the order in which they were declared in the class | |||
12343 | // definition. | |||
12344 | ||||
12345 | // Issue a warning if our implicit move assignment operator will move | |||
12346 | // from a virtual base more than once. | |||
12347 | checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); | |||
12348 | ||||
12349 | SynthesizedFunctionScope Scope(*this, MoveAssignOperator); | |||
12350 | ||||
12351 | // The exception specification is needed because we are defining the | |||
12352 | // function. | |||
12353 | ResolveExceptionSpec(CurrentLocation, | |||
12354 | MoveAssignOperator->getType()->castAs<FunctionProtoType>()); | |||
12355 | ||||
12356 | // Add a context note for diagnostics produced after this point. | |||
12357 | Scope.addContextNote(CurrentLocation); | |||
12358 | ||||
12359 | // The statements that form the synthesized function body. | |||
12360 | SmallVector<Stmt*, 8> Statements; | |||
12361 | ||||
12362 | // The parameter for the "other" object, which we are move from. | |||
12363 | ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); | |||
12364 | QualType OtherRefType = Other->getType()-> | |||
12365 | getAs<RValueReferenceType>()->getPointeeType(); | |||
12366 | ||||
12367 | // Our location for everything implicitly-generated. | |||
12368 | SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() | |||
12369 | ? MoveAssignOperator->getEndLoc() | |||
12370 | : MoveAssignOperator->getLocation(); | |||
12371 | ||||
12372 | // Builds a reference to the "other" object. | |||
12373 | RefBuilder OtherRef(Other, OtherRefType); | |||
12374 | // Cast to rvalue. | |||
12375 | MoveCastBuilder MoveOther(OtherRef); | |||
12376 | ||||
12377 | // Builds the "this" pointer. | |||
12378 | ThisBuilder This; | |||
12379 | ||||
12380 | // Assign base classes. | |||
12381 | bool Invalid = false; | |||
12382 | for (auto &Base : ClassDecl->bases()) { | |||
12383 | // C++11 [class.copy]p28: | |||
12384 | // It is unspecified whether subobjects representing virtual base classes | |||
12385 | // are assigned more than once by the implicitly-defined copy assignment | |||
12386 | // operator. | |||
12387 | // FIXME: Do not assign to a vbase that will be assigned by some other base | |||
12388 | // class. For a move-assignment, this can result in the vbase being moved | |||
12389 | // multiple times. | |||
12390 | ||||
12391 | // Form the assignment: | |||
12392 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); | |||
12393 | QualType BaseType = Base.getType().getUnqualifiedType(); | |||
12394 | if (!BaseType->isRecordType()) { | |||
12395 | Invalid = true; | |||
12396 | continue; | |||
12397 | } | |||
12398 | ||||
12399 | CXXCastPath BasePath; | |||
12400 | BasePath.push_back(&Base); | |||
12401 | ||||
12402 | // Construct the "from" expression, which is an implicit cast to the | |||
12403 | // appropriately-qualified base type. | |||
12404 | CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); | |||
12405 | ||||
12406 | // Dereference "this". | |||
12407 | DerefBuilder DerefThis(This); | |||
12408 | ||||
12409 | // Implicitly cast "this" to the appropriately-qualified base type. | |||
12410 | CastBuilder To(DerefThis, | |||
12411 | Context.getQualifiedType( | |||
12412 | BaseType, MoveAssignOperator->getMethodQualifiers()), | |||
12413 | VK_LValue, BasePath); | |||
12414 | ||||
12415 | // Build the move. | |||
12416 | StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, | |||
12417 | To, From, | |||
12418 | /*CopyingBaseSubobject=*/true, | |||
12419 | /*Copying=*/false); | |||
12420 | if (Move.isInvalid()) { | |||
12421 | MoveAssignOperator->setInvalidDecl(); | |||
12422 | return; | |||
12423 | } | |||
12424 | ||||
12425 | // Success! Record the move. | |||
12426 | Statements.push_back(Move.getAs<Expr>()); | |||
12427 | } | |||
12428 | ||||
12429 | // Assign non-static members. | |||
12430 | for (auto *Field : ClassDecl->fields()) { | |||
12431 | // FIXME: We should form some kind of AST representation for the implied | |||
12432 | // memcpy in a union copy operation. | |||
12433 | if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) | |||
12434 | continue; | |||
12435 | ||||
12436 | if (Field->isInvalidDecl()) { | |||
12437 | Invalid = true; | |||
12438 | continue; | |||
12439 | } | |||
12440 | ||||
12441 | // Check for members of reference type; we can't move those. | |||
12442 | if (Field->getType()->isReferenceType()) { | |||
12443 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
12444 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); | |||
12445 | Diag(Field->getLocation(), diag::note_declared_at); | |||
12446 | Invalid = true; | |||
12447 | continue; | |||
12448 | } | |||
12449 | ||||
12450 | // Check for members of const-qualified, non-class type. | |||
12451 | QualType BaseType = Context.getBaseElementType(Field->getType()); | |||
12452 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { | |||
12453 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | |||
12454 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); | |||
12455 | Diag(Field->getLocation(), diag::note_declared_at); | |||
12456 | Invalid = true; | |||
12457 | continue; | |||
12458 | } | |||
12459 | ||||
12460 | // Suppress assigning zero-width bitfields. | |||
12461 | if (Field->isZeroLengthBitField(Context)) | |||
12462 | continue; | |||
12463 | ||||
12464 | QualType FieldType = Field->getType().getNonReferenceType(); | |||
12465 | if (FieldType->isIncompleteArrayType()) { | |||
12466 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12467, __PRETTY_FUNCTION__)) | |||
12467 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12467, __PRETTY_FUNCTION__)); | |||
12468 | continue; | |||
12469 | } | |||
12470 | ||||
12471 | // Build references to the field in the object we're copying from and to. | |||
12472 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, | |||
12473 | LookupMemberName); | |||
12474 | MemberLookup.addDecl(Field); | |||
12475 | MemberLookup.resolveKind(); | |||
12476 | MemberBuilder From(MoveOther, OtherRefType, | |||
12477 | /*IsArrow=*/false, MemberLookup); | |||
12478 | MemberBuilder To(This, getCurrentThisType(), | |||
12479 | /*IsArrow=*/true, MemberLookup); | |||
12480 | ||||
12481 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12483, __PRETTY_FUNCTION__)) | |||
12482 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12483, __PRETTY_FUNCTION__)) | |||
12483 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12483, __PRETTY_FUNCTION__)); | |||
12484 | ||||
12485 | // Build the move of this field. | |||
12486 | StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, | |||
12487 | To, From, | |||
12488 | /*CopyingBaseSubobject=*/false, | |||
12489 | /*Copying=*/false); | |||
12490 | if (Move.isInvalid()) { | |||
12491 | MoveAssignOperator->setInvalidDecl(); | |||
12492 | return; | |||
12493 | } | |||
12494 | ||||
12495 | // Success! Record the copy. | |||
12496 | Statements.push_back(Move.getAs<Stmt>()); | |||
12497 | } | |||
12498 | ||||
12499 | if (!Invalid) { | |||
12500 | // Add a "return *this;" | |||
12501 | ExprResult ThisObj = | |||
12502 | CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); | |||
12503 | ||||
12504 | StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); | |||
12505 | if (Return.isInvalid()) | |||
12506 | Invalid = true; | |||
12507 | else | |||
12508 | Statements.push_back(Return.getAs<Stmt>()); | |||
12509 | } | |||
12510 | ||||
12511 | if (Invalid) { | |||
12512 | MoveAssignOperator->setInvalidDecl(); | |||
12513 | return; | |||
12514 | } | |||
12515 | ||||
12516 | StmtResult Body; | |||
12517 | { | |||
12518 | CompoundScopeRAII CompoundScope(*this); | |||
12519 | Body = ActOnCompoundStmt(Loc, Loc, Statements, | |||
12520 | /*isStmtExpr=*/false); | |||
12521 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12521, __PRETTY_FUNCTION__)); | |||
12522 | } | |||
12523 | MoveAssignOperator->setBody(Body.getAs<Stmt>()); | |||
12524 | MoveAssignOperator->markUsed(Context); | |||
12525 | ||||
12526 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12527 | L->CompletedImplicitDefinition(MoveAssignOperator); | |||
12528 | } | |||
12529 | } | |||
12530 | ||||
12531 | CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( | |||
12532 | CXXRecordDecl *ClassDecl) { | |||
12533 | // C++ [class.copy]p4: | |||
12534 | // If the class definition does not explicitly declare a copy | |||
12535 | // constructor, one is declared implicitly. | |||
12536 | assert(ClassDecl->needsImplicitCopyConstructor())((ClassDecl->needsImplicitCopyConstructor()) ? static_cast <void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12536, __PRETTY_FUNCTION__)); | |||
12537 | ||||
12538 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); | |||
12539 | if (DSM.isAlreadyBeingDeclared()) | |||
12540 | return nullptr; | |||
12541 | ||||
12542 | QualType ClassType = Context.getTypeDeclType(ClassDecl); | |||
12543 | QualType ArgType = ClassType; | |||
12544 | bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); | |||
12545 | if (Const) | |||
12546 | ArgType = ArgType.withConst(); | |||
12547 | ||||
12548 | if (Context.getLangOpts().OpenCLCPlusPlus) | |||
12549 | ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); | |||
12550 | ||||
12551 | ArgType = Context.getLValueReferenceType(ArgType); | |||
12552 | ||||
12553 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
12554 | CXXCopyConstructor, | |||
12555 | Const); | |||
12556 | ||||
12557 | DeclarationName Name | |||
12558 | = Context.DeclarationNames.getCXXConstructorName( | |||
12559 | Context.getCanonicalType(ClassType)); | |||
12560 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
12561 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
12562 | ||||
12563 | // An implicitly-declared copy constructor is an inline public | |||
12564 | // member of its class. | |||
12565 | CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( | |||
12566 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, | |||
12567 | ExplicitSpecifier(), | |||
12568 | /*isInline=*/true, | |||
12569 | /*isImplicitlyDeclared=*/true, Constexpr); | |||
12570 | CopyConstructor->setAccess(AS_public); | |||
12571 | CopyConstructor->setDefaulted(); | |||
12572 | ||||
12573 | if (getLangOpts().CUDA) { | |||
12574 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, | |||
12575 | CopyConstructor, | |||
12576 | /* ConstRHS */ Const, | |||
12577 | /* Diagnose */ false); | |||
12578 | } | |||
12579 | ||||
12580 | setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); | |||
12581 | ||||
12582 | // Add the parameter to the constructor. | |||
12583 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, | |||
12584 | ClassLoc, ClassLoc, | |||
12585 | /*IdentifierInfo=*/nullptr, | |||
12586 | ArgType, /*TInfo=*/nullptr, | |||
12587 | SC_None, nullptr); | |||
12588 | CopyConstructor->setParams(FromParam); | |||
12589 | ||||
12590 | CopyConstructor->setTrivial( | |||
12591 | ClassDecl->needsOverloadResolutionForCopyConstructor() | |||
12592 | ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) | |||
12593 | : ClassDecl->hasTrivialCopyConstructor()); | |||
12594 | ||||
12595 | CopyConstructor->setTrivialForCall( | |||
12596 | ClassDecl->hasAttr<TrivialABIAttr>() || | |||
12597 | (ClassDecl->needsOverloadResolutionForCopyConstructor() | |||
12598 | ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, | |||
12599 | TAH_ConsiderTrivialABI) | |||
12600 | : ClassDecl->hasTrivialCopyConstructorForCall())); | |||
12601 | ||||
12602 | // Note that we have declared this constructor. | |||
12603 | ++getASTContext().NumImplicitCopyConstructorsDeclared; | |||
12604 | ||||
12605 | Scope *S = getScopeForContext(ClassDecl); | |||
12606 | CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); | |||
12607 | ||||
12608 | if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { | |||
12609 | ClassDecl->setImplicitCopyConstructorIsDeleted(); | |||
12610 | SetDeclDeleted(CopyConstructor, ClassLoc); | |||
12611 | } | |||
12612 | ||||
12613 | if (S) | |||
12614 | PushOnScopeChains(CopyConstructor, S, false); | |||
12615 | ClassDecl->addDecl(CopyConstructor); | |||
12616 | ||||
12617 | return CopyConstructor; | |||
12618 | } | |||
12619 | ||||
12620 | void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, | |||
12621 | CXXConstructorDecl *CopyConstructor) { | |||
12622 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12626, __PRETTY_FUNCTION__)) | |||
12623 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12626, __PRETTY_FUNCTION__)) | |||
12624 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12626, __PRETTY_FUNCTION__)) | |||
12625 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12626, __PRETTY_FUNCTION__)) | |||
12626 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12626, __PRETTY_FUNCTION__)); | |||
12627 | if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) | |||
12628 | return; | |||
12629 | ||||
12630 | CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); | |||
12631 | assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")((ClassDecl && "DefineImplicitCopyConstructor - invalid constructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12631, __PRETTY_FUNCTION__)); | |||
12632 | ||||
12633 | SynthesizedFunctionScope Scope(*this, CopyConstructor); | |||
12634 | ||||
12635 | // The exception specification is needed because we are defining the | |||
12636 | // function. | |||
12637 | ResolveExceptionSpec(CurrentLocation, | |||
12638 | CopyConstructor->getType()->castAs<FunctionProtoType>()); | |||
12639 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
12640 | ||||
12641 | // Add a context note for diagnostics produced after this point. | |||
12642 | Scope.addContextNote(CurrentLocation); | |||
12643 | ||||
12644 | // C++11 [class.copy]p7: | |||
12645 | // The [definition of an implicitly declared copy constructor] is | |||
12646 | // deprecated if the class has a user-declared copy assignment operator | |||
12647 | // or a user-declared destructor. | |||
12648 | if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) | |||
12649 | diagnoseDeprecatedCopyOperation(*this, CopyConstructor); | |||
12650 | ||||
12651 | if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { | |||
12652 | CopyConstructor->setInvalidDecl(); | |||
12653 | } else { | |||
12654 | SourceLocation Loc = CopyConstructor->getEndLoc().isValid() | |||
12655 | ? CopyConstructor->getEndLoc() | |||
12656 | : CopyConstructor->getLocation(); | |||
12657 | Sema::CompoundScopeRAII CompoundScope(*this); | |||
12658 | CopyConstructor->setBody( | |||
12659 | ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); | |||
12660 | CopyConstructor->markUsed(Context); | |||
12661 | } | |||
12662 | ||||
12663 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12664 | L->CompletedImplicitDefinition(CopyConstructor); | |||
12665 | } | |||
12666 | } | |||
12667 | ||||
12668 | CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( | |||
12669 | CXXRecordDecl *ClassDecl) { | |||
12670 | assert(ClassDecl->needsImplicitMoveConstructor())((ClassDecl->needsImplicitMoveConstructor()) ? static_cast <void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12670, __PRETTY_FUNCTION__)); | |||
12671 | ||||
12672 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); | |||
12673 | if (DSM.isAlreadyBeingDeclared()) | |||
12674 | return nullptr; | |||
12675 | ||||
12676 | QualType ClassType = Context.getTypeDeclType(ClassDecl); | |||
12677 | ||||
12678 | QualType ArgType = ClassType; | |||
12679 | if (Context.getLangOpts().OpenCLCPlusPlus) | |||
12680 | ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); | |||
12681 | ArgType = Context.getRValueReferenceType(ArgType); | |||
12682 | ||||
12683 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
12684 | CXXMoveConstructor, | |||
12685 | false); | |||
12686 | ||||
12687 | DeclarationName Name | |||
12688 | = Context.DeclarationNames.getCXXConstructorName( | |||
12689 | Context.getCanonicalType(ClassType)); | |||
12690 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
12691 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
12692 | ||||
12693 | // C++11 [class.copy]p11: | |||
12694 | // An implicitly-declared copy/move constructor is an inline public | |||
12695 | // member of its class. | |||
12696 | CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( | |||
12697 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, | |||
12698 | ExplicitSpecifier(), | |||
12699 | /*isInline=*/true, | |||
12700 | /*isImplicitlyDeclared=*/true, Constexpr); | |||
12701 | MoveConstructor->setAccess(AS_public); | |||
12702 | MoveConstructor->setDefaulted(); | |||
12703 | ||||
12704 | if (getLangOpts().CUDA) { | |||
12705 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, | |||
12706 | MoveConstructor, | |||
12707 | /* ConstRHS */ false, | |||
12708 | /* Diagnose */ false); | |||
12709 | } | |||
12710 | ||||
12711 | setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); | |||
12712 | ||||
12713 | // Add the parameter to the constructor. | |||
12714 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, | |||
12715 | ClassLoc, ClassLoc, | |||
12716 | /*IdentifierInfo=*/nullptr, | |||
12717 | ArgType, /*TInfo=*/nullptr, | |||
12718 | SC_None, nullptr); | |||
12719 | MoveConstructor->setParams(FromParam); | |||
12720 | ||||
12721 | MoveConstructor->setTrivial( | |||
12722 | ClassDecl->needsOverloadResolutionForMoveConstructor() | |||
12723 | ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) | |||
12724 | : ClassDecl->hasTrivialMoveConstructor()); | |||
12725 | ||||
12726 | MoveConstructor->setTrivialForCall( | |||
12727 | ClassDecl->hasAttr<TrivialABIAttr>() || | |||
12728 | (ClassDecl->needsOverloadResolutionForMoveConstructor() | |||
12729 | ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, | |||
12730 | TAH_ConsiderTrivialABI) | |||
12731 | : ClassDecl->hasTrivialMoveConstructorForCall())); | |||
12732 | ||||
12733 | // Note that we have declared this constructor. | |||
12734 | ++getASTContext().NumImplicitMoveConstructorsDeclared; | |||
12735 | ||||
12736 | Scope *S = getScopeForContext(ClassDecl); | |||
12737 | CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); | |||
12738 | ||||
12739 | if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { | |||
12740 | ClassDecl->setImplicitMoveConstructorIsDeleted(); | |||
12741 | SetDeclDeleted(MoveConstructor, ClassLoc); | |||
12742 | } | |||
12743 | ||||
12744 | if (S) | |||
12745 | PushOnScopeChains(MoveConstructor, S, false); | |||
12746 | ClassDecl->addDecl(MoveConstructor); | |||
12747 | ||||
12748 | return MoveConstructor; | |||
12749 | } | |||
12750 | ||||
12751 | void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, | |||
12752 | CXXConstructorDecl *MoveConstructor) { | |||
12753 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12757, __PRETTY_FUNCTION__)) | |||
12754 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12757, __PRETTY_FUNCTION__)) | |||
12755 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12757, __PRETTY_FUNCTION__)) | |||
12756 | !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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12757, __PRETTY_FUNCTION__)) | |||
12757 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12757, __PRETTY_FUNCTION__)); | |||
12758 | if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) | |||
12759 | return; | |||
12760 | ||||
12761 | CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); | |||
12762 | assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")((ClassDecl && "DefineImplicitMoveConstructor - invalid constructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12762, __PRETTY_FUNCTION__)); | |||
12763 | ||||
12764 | SynthesizedFunctionScope Scope(*this, MoveConstructor); | |||
12765 | ||||
12766 | // The exception specification is needed because we are defining the | |||
12767 | // function. | |||
12768 | ResolveExceptionSpec(CurrentLocation, | |||
12769 | MoveConstructor->getType()->castAs<FunctionProtoType>()); | |||
12770 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
12771 | ||||
12772 | // Add a context note for diagnostics produced after this point. | |||
12773 | Scope.addContextNote(CurrentLocation); | |||
12774 | ||||
12775 | if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { | |||
12776 | MoveConstructor->setInvalidDecl(); | |||
12777 | } else { | |||
12778 | SourceLocation Loc = MoveConstructor->getEndLoc().isValid() | |||
12779 | ? MoveConstructor->getEndLoc() | |||
12780 | : MoveConstructor->getLocation(); | |||
12781 | Sema::CompoundScopeRAII CompoundScope(*this); | |||
12782 | MoveConstructor->setBody(ActOnCompoundStmt( | |||
12783 | Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); | |||
12784 | MoveConstructor->markUsed(Context); | |||
12785 | } | |||
12786 | ||||
12787 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12788 | L->CompletedImplicitDefinition(MoveConstructor); | |||
12789 | } | |||
12790 | } | |||
12791 | ||||
12792 | bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { | |||
12793 | return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); | |||
12794 | } | |||
12795 | ||||
12796 | void Sema::DefineImplicitLambdaToFunctionPointerConversion( | |||
12797 | SourceLocation CurrentLocation, | |||
12798 | CXXConversionDecl *Conv) { | |||
12799 | SynthesizedFunctionScope Scope(*this, Conv); | |||
12800 | assert(!Conv->getReturnType()->isUndeducedType())((!Conv->getReturnType()->isUndeducedType()) ? static_cast <void> (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12800, __PRETTY_FUNCTION__)); | |||
12801 | ||||
12802 | CXXRecordDecl *Lambda = Conv->getParent(); | |||
12803 | FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); | |||
12804 | FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); | |||
12805 | ||||
12806 | if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { | |||
12807 | CallOp = InstantiateFunctionDeclaration( | |||
12808 | CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); | |||
12809 | if (!CallOp) | |||
12810 | return; | |||
12811 | ||||
12812 | Invoker = InstantiateFunctionDeclaration( | |||
12813 | Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); | |||
12814 | if (!Invoker) | |||
12815 | return; | |||
12816 | } | |||
12817 | ||||
12818 | if (CallOp->isInvalidDecl()) | |||
12819 | return; | |||
12820 | ||||
12821 | // Mark the call operator referenced (and add to pending instantiations | |||
12822 | // if necessary). | |||
12823 | // For both the conversion and static-invoker template specializations | |||
12824 | // we construct their body's in this function, so no need to add them | |||
12825 | // to the PendingInstantiations. | |||
12826 | MarkFunctionReferenced(CurrentLocation, CallOp); | |||
12827 | ||||
12828 | // Fill in the __invoke function with a dummy implementation. IR generation | |||
12829 | // will fill in the actual details. Update its type in case it contained | |||
12830 | // an 'auto'. | |||
12831 | Invoker->markUsed(Context); | |||
12832 | Invoker->setReferenced(); | |||
12833 | Invoker->setType(Conv->getReturnType()->getPointeeType()); | |||
12834 | Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); | |||
12835 | ||||
12836 | // Construct the body of the conversion function { return __invoke; }. | |||
12837 | Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), | |||
12838 | VK_LValue, Conv->getLocation()).get(); | |||
12839 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12839, __PRETTY_FUNCTION__)); | |||
12840 | Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); | |||
12841 | Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), | |||
12842 | Conv->getLocation())); | |||
12843 | Conv->markUsed(Context); | |||
12844 | Conv->setReferenced(); | |||
12845 | ||||
12846 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12847 | L->CompletedImplicitDefinition(Conv); | |||
12848 | L->CompletedImplicitDefinition(Invoker); | |||
12849 | } | |||
12850 | } | |||
12851 | ||||
12852 | ||||
12853 | ||||
12854 | void Sema::DefineImplicitLambdaToBlockPointerConversion( | |||
12855 | SourceLocation CurrentLocation, | |||
12856 | CXXConversionDecl *Conv) | |||
12857 | { | |||
12858 | assert(!Conv->getParent()->isGenericLambda())((!Conv->getParent()->isGenericLambda()) ? static_cast< void> (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12858, __PRETTY_FUNCTION__)); | |||
12859 | ||||
12860 | SynthesizedFunctionScope Scope(*this, Conv); | |||
12861 | ||||
12862 | // Copy-initialize the lambda object as needed to capture it. | |||
12863 | Expr *This = ActOnCXXThis(CurrentLocation).get(); | |||
12864 | Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); | |||
12865 | ||||
12866 | ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, | |||
12867 | Conv->getLocation(), | |||
12868 | Conv, DerefThis); | |||
12869 | ||||
12870 | // If we're not under ARC, make sure we still get the _Block_copy/autorelease | |||
12871 | // behavior. Note that only the general conversion function does this | |||
12872 | // (since it's unusable otherwise); in the case where we inline the | |||
12873 | // block literal, it has block literal lifetime semantics. | |||
12874 | if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) | |||
12875 | BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), | |||
12876 | CK_CopyAndAutoreleaseBlockObject, | |||
12877 | BuildBlock.get(), nullptr, VK_RValue); | |||
12878 | ||||
12879 | if (BuildBlock.isInvalid()) { | |||
12880 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); | |||
12881 | Conv->setInvalidDecl(); | |||
12882 | return; | |||
12883 | } | |||
12884 | ||||
12885 | // Create the return statement that returns the block from the conversion | |||
12886 | // function. | |||
12887 | StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); | |||
12888 | if (Return.isInvalid()) { | |||
12889 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); | |||
12890 | Conv->setInvalidDecl(); | |||
12891 | return; | |||
12892 | } | |||
12893 | ||||
12894 | // Set the body of the conversion function. | |||
12895 | Stmt *ReturnS = Return.get(); | |||
12896 | Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), | |||
12897 | Conv->getLocation())); | |||
12898 | Conv->markUsed(Context); | |||
12899 | ||||
12900 | // We're done; notify the mutation listener, if any. | |||
12901 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
12902 | L->CompletedImplicitDefinition(Conv); | |||
12903 | } | |||
12904 | } | |||
12905 | ||||
12906 | /// Determine whether the given list arguments contains exactly one | |||
12907 | /// "real" (non-default) argument. | |||
12908 | static bool hasOneRealArgument(MultiExprArg Args) { | |||
12909 | switch (Args.size()) { | |||
12910 | case 0: | |||
12911 | return false; | |||
12912 | ||||
12913 | default: | |||
12914 | if (!Args[1]->isDefaultArgument()) | |||
12915 | return false; | |||
12916 | ||||
12917 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
12918 | case 1: | |||
12919 | return !Args[0]->isDefaultArgument(); | |||
12920 | } | |||
12921 | ||||
12922 | return false; | |||
12923 | } | |||
12924 | ||||
12925 | ExprResult | |||
12926 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
12927 | NamedDecl *FoundDecl, | |||
12928 | CXXConstructorDecl *Constructor, | |||
12929 | MultiExprArg ExprArgs, | |||
12930 | bool HadMultipleCandidates, | |||
12931 | bool IsListInitialization, | |||
12932 | bool IsStdInitListInitialization, | |||
12933 | bool RequiresZeroInit, | |||
12934 | unsigned ConstructKind, | |||
12935 | SourceRange ParenRange) { | |||
12936 | bool Elidable = false; | |||
12937 | ||||
12938 | // C++0x [class.copy]p34: | |||
12939 | // When certain criteria are met, an implementation is allowed to | |||
12940 | // omit the copy/move construction of a class object, even if the | |||
12941 | // copy/move constructor and/or destructor for the object have | |||
12942 | // side effects. [...] | |||
12943 | // - when a temporary class object that has not been bound to a | |||
12944 | // reference (12.2) would be copied/moved to a class object | |||
12945 | // with the same cv-unqualified type, the copy/move operation | |||
12946 | // can be omitted by constructing the temporary object | |||
12947 | // directly into the target of the omitted copy/move | |||
12948 | if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && | |||
12949 | Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { | |||
12950 | Expr *SubExpr = ExprArgs[0]; | |||
12951 | Elidable = SubExpr->isTemporaryObject( | |||
12952 | Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); | |||
12953 | } | |||
12954 | ||||
12955 | return BuildCXXConstructExpr(ConstructLoc, DeclInitType, | |||
12956 | FoundDecl, Constructor, | |||
12957 | Elidable, ExprArgs, HadMultipleCandidates, | |||
12958 | IsListInitialization, | |||
12959 | IsStdInitListInitialization, RequiresZeroInit, | |||
12960 | ConstructKind, ParenRange); | |||
12961 | } | |||
12962 | ||||
12963 | ExprResult | |||
12964 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
12965 | NamedDecl *FoundDecl, | |||
12966 | CXXConstructorDecl *Constructor, | |||
12967 | bool Elidable, | |||
12968 | MultiExprArg ExprArgs, | |||
12969 | bool HadMultipleCandidates, | |||
12970 | bool IsListInitialization, | |||
12971 | bool IsStdInitListInitialization, | |||
12972 | bool RequiresZeroInit, | |||
12973 | unsigned ConstructKind, | |||
12974 | SourceRange ParenRange) { | |||
12975 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { | |||
12976 | Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); | |||
12977 | if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) | |||
12978 | return ExprError(); | |||
12979 | } | |||
12980 | ||||
12981 | return BuildCXXConstructExpr( | |||
12982 | ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, | |||
12983 | HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, | |||
12984 | RequiresZeroInit, ConstructKind, ParenRange); | |||
12985 | } | |||
12986 | ||||
12987 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, | |||
12988 | /// including handling of its default argument expressions. | |||
12989 | ExprResult | |||
12990 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
12991 | CXXConstructorDecl *Constructor, | |||
12992 | bool Elidable, | |||
12993 | MultiExprArg ExprArgs, | |||
12994 | bool HadMultipleCandidates, | |||
12995 | bool IsListInitialization, | |||
12996 | bool IsStdInitListInitialization, | |||
12997 | bool RequiresZeroInit, | |||
12998 | unsigned ConstructKind, | |||
12999 | SourceRange ParenRange) { | |||
13000 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13003, __PRETTY_FUNCTION__)) | |||
13001 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13003, __PRETTY_FUNCTION__)) | |||
13002 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13003, __PRETTY_FUNCTION__)) | |||
13003 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13003, __PRETTY_FUNCTION__)); | |||
13004 | MarkFunctionReferenced(ConstructLoc, Constructor); | |||
13005 | if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) | |||
13006 | return ExprError(); | |||
13007 | ||||
13008 | return CXXConstructExpr::Create( | |||
13009 | Context, DeclInitType, ConstructLoc, Constructor, Elidable, | |||
13010 | ExprArgs, HadMultipleCandidates, IsListInitialization, | |||
13011 | IsStdInitListInitialization, RequiresZeroInit, | |||
13012 | static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), | |||
13013 | ParenRange); | |||
13014 | } | |||
13015 | ||||
13016 | ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { | |||
13017 | assert(Field->hasInClassInitializer())((Field->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Field->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13017, __PRETTY_FUNCTION__)); | |||
13018 | ||||
13019 | // If we already have the in-class initializer nothing needs to be done. | |||
13020 | if (Field->getInClassInitializer()) | |||
13021 | return CXXDefaultInitExpr::Create(Context, Loc, Field); | |||
13022 | ||||
13023 | // If we might have already tried and failed to instantiate, don't try again. | |||
13024 | if (Field->isInvalidDecl()) | |||
13025 | return ExprError(); | |||
13026 | ||||
13027 | // Maybe we haven't instantiated the in-class initializer. Go check the | |||
13028 | // pattern FieldDecl to see if it has one. | |||
13029 | CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); | |||
13030 | ||||
13031 | if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { | |||
13032 | CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); | |||
13033 | DeclContext::lookup_result Lookup = | |||
13034 | ClassPattern->lookup(Field->getDeclName()); | |||
13035 | ||||
13036 | // Lookup can return at most two results: the pattern for the field, or the | |||
13037 | // injected class name of the parent record. No other member can have the | |||
13038 | // same name as the field. | |||
13039 | // In modules mode, lookup can return multiple results (coming from | |||
13040 | // different modules). | |||
13041 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13042, __PRETTY_FUNCTION__)) | |||
13042 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13042, __PRETTY_FUNCTION__)); | |||
13043 | FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); | |||
13044 | if (!Pattern) { | |||
13045 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13046, __PRETTY_FUNCTION__)) | |||
13046 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13046, __PRETTY_FUNCTION__)); | |||
13047 | for (auto L : Lookup) | |||
13048 | if (isa<FieldDecl>(L)) { | |||
13049 | Pattern = cast<FieldDecl>(L); | |||
13050 | break; | |||
13051 | } | |||
13052 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13052, __PRETTY_FUNCTION__)); | |||
13053 | } | |||
13054 | ||||
13055 | if (!Pattern->hasInClassInitializer() || | |||
13056 | InstantiateInClassInitializer(Loc, Field, Pattern, | |||
13057 | getTemplateInstantiationArgs(Field))) { | |||
13058 | // Don't diagnose this again. | |||
13059 | Field->setInvalidDecl(); | |||
13060 | return ExprError(); | |||
13061 | } | |||
13062 | return CXXDefaultInitExpr::Create(Context, Loc, Field); | |||
13063 | } | |||
13064 | ||||
13065 | // DR1351: | |||
13066 | // If the brace-or-equal-initializer of a non-static data member | |||
13067 | // invokes a defaulted default constructor of its class or of an | |||
13068 | // enclosing class in a potentially evaluated subexpression, the | |||
13069 | // program is ill-formed. | |||
13070 | // | |||
13071 | // This resolution is unworkable: the exception specification of the | |||
13072 | // default constructor can be needed in an unevaluated context, in | |||
13073 | // particular, in the operand of a noexcept-expression, and we can be | |||
13074 | // unable to compute an exception specification for an enclosed class. | |||
13075 | // | |||
13076 | // Any attempt to resolve the exception specification of a defaulted default | |||
13077 | // constructor before the initializer is lexically complete will ultimately | |||
13078 | // come here at which point we can diagnose it. | |||
13079 | RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); | |||
13080 | Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) | |||
13081 | << OutermostClass << Field; | |||
13082 | Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); | |||
13083 | // Recover by marking the field invalid, unless we're in a SFINAE context. | |||
13084 | if (!isSFINAEContext()) | |||
13085 | Field->setInvalidDecl(); | |||
13086 | return ExprError(); | |||
13087 | } | |||
13088 | ||||
13089 | void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { | |||
13090 | if (VD->isInvalidDecl()) return; | |||
13091 | ||||
13092 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); | |||
13093 | if (ClassDecl->isInvalidDecl()) return; | |||
13094 | if (ClassDecl->hasIrrelevantDestructor()) return; | |||
13095 | if (ClassDecl->isDependentContext()) return; | |||
13096 | ||||
13097 | if (VD->isNoDestroy(getASTContext())) | |||
13098 | return; | |||
13099 | ||||
13100 | CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); | |||
13101 | MarkFunctionReferenced(VD->getLocation(), Destructor); | |||
13102 | CheckDestructorAccess(VD->getLocation(), Destructor, | |||
13103 | PDiag(diag::err_access_dtor_var) | |||
13104 | << VD->getDeclName() | |||
13105 | << VD->getType()); | |||
13106 | DiagnoseUseOfDecl(Destructor, VD->getLocation()); | |||
13107 | ||||
13108 | if (Destructor->isTrivial()) return; | |||
13109 | if (!VD->hasGlobalStorage()) return; | |||
13110 | ||||
13111 | // Emit warning for non-trivial dtor in global scope (a real global, | |||
13112 | // class-static, function-static). | |||
13113 | Diag(VD->getLocation(), diag::warn_exit_time_destructor); | |||
13114 | ||||
13115 | // TODO: this should be re-enabled for static locals by !CXAAtExit | |||
13116 | if (!VD->isStaticLocal()) | |||
13117 | Diag(VD->getLocation(), diag::warn_global_destructor); | |||
13118 | } | |||
13119 | ||||
13120 | /// Given a constructor and the set of arguments provided for the | |||
13121 | /// constructor, convert the arguments and add any required default arguments | |||
13122 | /// to form a proper call to this constructor. | |||
13123 | /// | |||
13124 | /// \returns true if an error occurred, false otherwise. | |||
13125 | bool | |||
13126 | Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, | |||
13127 | MultiExprArg ArgsPtr, | |||
13128 | SourceLocation Loc, | |||
13129 | SmallVectorImpl<Expr*> &ConvertedArgs, | |||
13130 | bool AllowExplicit, | |||
13131 | bool IsListInitialization) { | |||
13132 | // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. | |||
13133 | unsigned NumArgs = ArgsPtr.size(); | |||
13134 | Expr **Args = ArgsPtr.data(); | |||
13135 | ||||
13136 | const FunctionProtoType *Proto | |||
13137 | = Constructor->getType()->getAs<FunctionProtoType>(); | |||
13138 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13138, __PRETTY_FUNCTION__)); | |||
13139 | unsigned NumParams = Proto->getNumParams(); | |||
13140 | ||||
13141 | // If too few arguments are available, we'll fill in the rest with defaults. | |||
13142 | if (NumArgs < NumParams) | |||
13143 | ConvertedArgs.reserve(NumParams); | |||
13144 | else | |||
13145 | ConvertedArgs.reserve(NumArgs); | |||
13146 | ||||
13147 | VariadicCallType CallType = | |||
13148 | Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; | |||
13149 | SmallVector<Expr *, 8> AllArgs; | |||
13150 | bool Invalid = GatherArgumentsForCall(Loc, Constructor, | |||
13151 | Proto, 0, | |||
13152 | llvm::makeArrayRef(Args, NumArgs), | |||
13153 | AllArgs, | |||
13154 | CallType, AllowExplicit, | |||
13155 | IsListInitialization); | |||
13156 | ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); | |||
13157 | ||||
13158 | DiagnoseSentinelCalls(Constructor, Loc, AllArgs); | |||
13159 | ||||
13160 | CheckConstructorCall(Constructor, | |||
13161 | llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), | |||
13162 | Proto, Loc); | |||
13163 | ||||
13164 | return Invalid; | |||
13165 | } | |||
13166 | ||||
13167 | static inline bool | |||
13168 | CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, | |||
13169 | const FunctionDecl *FnDecl) { | |||
13170 | const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); | |||
13171 | if (isa<NamespaceDecl>(DC)) { | |||
13172 | return SemaRef.Diag(FnDecl->getLocation(), | |||
13173 | diag::err_operator_new_delete_declared_in_namespace) | |||
13174 | << FnDecl->getDeclName(); | |||
13175 | } | |||
13176 | ||||
13177 | if (isa<TranslationUnitDecl>(DC) && | |||
13178 | FnDecl->getStorageClass() == SC_Static) { | |||
13179 | return SemaRef.Diag(FnDecl->getLocation(), | |||
13180 | diag::err_operator_new_delete_declared_static) | |||
13181 | << FnDecl->getDeclName(); | |||
13182 | } | |||
13183 | ||||
13184 | return false; | |||
13185 | } | |||
13186 | ||||
13187 | static QualType | |||
13188 | RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { | |||
13189 | QualType QTy = PtrTy->getPointeeType(); | |||
13190 | QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); | |||
13191 | return SemaRef.Context.getPointerType(QTy); | |||
13192 | } | |||
13193 | ||||
13194 | static inline bool | |||
13195 | CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, | |||
13196 | CanQualType ExpectedResultType, | |||
13197 | CanQualType ExpectedFirstParamType, | |||
13198 | unsigned DependentParamTypeDiag, | |||
13199 | unsigned InvalidParamTypeDiag) { | |||
13200 | QualType ResultType = | |||
13201 | FnDecl->getType()->getAs<FunctionType>()->getReturnType(); | |||
13202 | ||||
13203 | // Check that the result type is not dependent. | |||
13204 | if (ResultType->isDependentType()) | |||
13205 | return SemaRef.Diag(FnDecl->getLocation(), | |||
13206 | diag::err_operator_new_delete_dependent_result_type) | |||
13207 | << FnDecl->getDeclName() << ExpectedResultType; | |||
13208 | ||||
13209 | // OpenCL C++: the operator is valid on any address space. | |||
13210 | if (SemaRef.getLangOpts().OpenCLCPlusPlus) { | |||
13211 | if (auto *PtrTy = ResultType->getAs<PointerType>()) { | |||
13212 | ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); | |||
13213 | } | |||
13214 | } | |||
13215 | ||||
13216 | // Check that the result type is what we expect. | |||
13217 | if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) | |||
13218 | return SemaRef.Diag(FnDecl->getLocation(), | |||
13219 | diag::err_operator_new_delete_invalid_result_type) | |||
13220 | << FnDecl->getDeclName() << ExpectedResultType; | |||
13221 | ||||
13222 | // A function template must have at least 2 parameters. | |||
13223 | if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) | |||
13224 | return SemaRef.Diag(FnDecl->getLocation(), | |||
13225 | diag::err_operator_new_delete_template_too_few_parameters) | |||
13226 | << FnDecl->getDeclName(); | |||
13227 | ||||
13228 | // The function decl must have at least 1 parameter. | |||
13229 | if (FnDecl->getNumParams() == 0) | |||
13230 | return SemaRef.Diag(FnDecl->getLocation(), | |||
13231 | diag::err_operator_new_delete_too_few_parameters) | |||
13232 | << FnDecl->getDeclName(); | |||
13233 | ||||
13234 | // Check the first parameter type is not dependent. | |||
13235 | QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); | |||
13236 | if (FirstParamType->isDependentType()) | |||
13237 | return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) | |||
13238 | << FnDecl->getDeclName() << ExpectedFirstParamType; | |||
13239 | ||||
13240 | // Check that the first parameter type is what we expect. | |||
13241 | if (SemaRef.getLangOpts().OpenCLCPlusPlus) { | |||
13242 | // OpenCL C++: the operator is valid on any address space. | |||
13243 | if (auto *PtrTy = | |||
13244 | FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { | |||
13245 | FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); | |||
13246 | } | |||
13247 | } | |||
13248 | if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != | |||
13249 | ExpectedFirstParamType) | |||
13250 | return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) | |||
13251 | << FnDecl->getDeclName() << ExpectedFirstParamType; | |||
13252 | ||||
13253 | return false; | |||
13254 | } | |||
13255 | ||||
13256 | static bool | |||
13257 | CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { | |||
13258 | // C++ [basic.stc.dynamic.allocation]p1: | |||
13259 | // A program is ill-formed if an allocation function is declared in a | |||
13260 | // namespace scope other than global scope or declared static in global | |||
13261 | // scope. | |||
13262 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) | |||
13263 | return true; | |||
13264 | ||||
13265 | CanQualType SizeTy = | |||
13266 | SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); | |||
13267 | ||||
13268 | // C++ [basic.stc.dynamic.allocation]p1: | |||
13269 | // The return type shall be void*. The first parameter shall have type | |||
13270 | // std::size_t. | |||
13271 | if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, | |||
13272 | SizeTy, | |||
13273 | diag::err_operator_new_dependent_param_type, | |||
13274 | diag::err_operator_new_param_type)) | |||
13275 | return true; | |||
13276 | ||||
13277 | // C++ [basic.stc.dynamic.allocation]p1: | |||
13278 | // The first parameter shall not have an associated default argument. | |||
13279 | if (FnDecl->getParamDecl(0)->hasDefaultArg()) | |||
13280 | return SemaRef.Diag(FnDecl->getLocation(), | |||
13281 | diag::err_operator_new_default_arg) | |||
13282 | << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); | |||
13283 | ||||
13284 | return false; | |||
13285 | } | |||
13286 | ||||
13287 | static bool | |||
13288 | CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { | |||
13289 | // C++ [basic.stc.dynamic.deallocation]p1: | |||
13290 | // A program is ill-formed if deallocation functions are declared in a | |||
13291 | // namespace scope other than global scope or declared static in global | |||
13292 | // scope. | |||
13293 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) | |||
13294 | return true; | |||
13295 | ||||
13296 | auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); | |||
13297 | ||||
13298 | // C++ P0722: | |||
13299 | // Within a class C, the first parameter of a destroying operator delete | |||
13300 | // shall be of type C *. The first parameter of any other deallocation | |||
13301 | // function shall be of type void *. | |||
13302 | CanQualType ExpectedFirstParamType = | |||
13303 | MD && MD->isDestroyingOperatorDelete() | |||
13304 | ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( | |||
13305 | SemaRef.Context.getRecordType(MD->getParent()))) | |||
13306 | : SemaRef.Context.VoidPtrTy; | |||
13307 | ||||
13308 | // C++ [basic.stc.dynamic.deallocation]p2: | |||
13309 | // Each deallocation function shall return void | |||
13310 | if (CheckOperatorNewDeleteTypes( | |||
13311 | SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, | |||
13312 | diag::err_operator_delete_dependent_param_type, | |||
13313 | diag::err_operator_delete_param_type)) | |||
13314 | return true; | |||
13315 | ||||
13316 | // C++ P0722: | |||
13317 | // A destroying operator delete shall be a usual deallocation function. | |||
13318 | if (MD && !MD->getParent()->isDependentContext() && | |||
13319 | MD->isDestroyingOperatorDelete() && | |||
13320 | !SemaRef.isUsualDeallocationFunction(MD)) { | |||
13321 | SemaRef.Diag(MD->getLocation(), | |||
13322 | diag::err_destroying_operator_delete_not_usual); | |||
13323 | return true; | |||
13324 | } | |||
13325 | ||||
13326 | return false; | |||
13327 | } | |||
13328 | ||||
13329 | /// CheckOverloadedOperatorDeclaration - Check whether the declaration | |||
13330 | /// of this overloaded operator is well-formed. If so, returns false; | |||
13331 | /// otherwise, emits appropriate diagnostics and returns true. | |||
13332 | bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { | |||
13333 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13334, __PRETTY_FUNCTION__)) | |||
13334 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13334, __PRETTY_FUNCTION__)); | |||
13335 | ||||
13336 | OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); | |||
13337 | ||||
13338 | // C++ [over.oper]p5: | |||
13339 | // The allocation and deallocation functions, operator new, | |||
13340 | // operator new[], operator delete and operator delete[], are | |||
13341 | // described completely in 3.7.3. The attributes and restrictions | |||
13342 | // found in the rest of this subclause do not apply to them unless | |||
13343 | // explicitly stated in 3.7.3. | |||
13344 | if (Op == OO_Delete || Op == OO_Array_Delete) | |||
13345 | return CheckOperatorDeleteDeclaration(*this, FnDecl); | |||
13346 | ||||
13347 | if (Op == OO_New || Op == OO_Array_New) | |||
13348 | return CheckOperatorNewDeclaration(*this, FnDecl); | |||
13349 | ||||
13350 | // C++ [over.oper]p6: | |||
13351 | // An operator function shall either be a non-static member | |||
13352 | // function or be a non-member function and have at least one | |||
13353 | // parameter whose type is a class, a reference to a class, an | |||
13354 | // enumeration, or a reference to an enumeration. | |||
13355 | if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { | |||
13356 | if (MethodDecl->isStatic()) | |||
13357 | return Diag(FnDecl->getLocation(), | |||
13358 | diag::err_operator_overload_static) << FnDecl->getDeclName(); | |||
13359 | } else { | |||
13360 | bool ClassOrEnumParam = false; | |||
13361 | for (auto Param : FnDecl->parameters()) { | |||
13362 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
13363 | if (ParamType->isDependentType() || ParamType->isRecordType() || | |||
13364 | ParamType->isEnumeralType()) { | |||
13365 | ClassOrEnumParam = true; | |||
13366 | break; | |||
13367 | } | |||
13368 | } | |||
13369 | ||||
13370 | if (!ClassOrEnumParam) | |||
13371 | return Diag(FnDecl->getLocation(), | |||
13372 | diag::err_operator_overload_needs_class_or_enum) | |||
13373 | << FnDecl->getDeclName(); | |||
13374 | } | |||
13375 | ||||
13376 | // C++ [over.oper]p8: | |||
13377 | // An operator function cannot have default arguments (8.3.6), | |||
13378 | // except where explicitly stated below. | |||
13379 | // | |||
13380 | // Only the function-call operator allows default arguments | |||
13381 | // (C++ [over.call]p1). | |||
13382 | if (Op != OO_Call) { | |||
13383 | for (auto Param : FnDecl->parameters()) { | |||
13384 | if (Param->hasDefaultArg()) | |||
13385 | return Diag(Param->getLocation(), | |||
13386 | diag::err_operator_overload_default_arg) | |||
13387 | << FnDecl->getDeclName() << Param->getDefaultArgRange(); | |||
13388 | } | |||
13389 | } | |||
13390 | ||||
13391 | static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { | |||
13392 | { false, false, false } | |||
13393 | #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ | |||
13394 | , { Unary, Binary, MemberOnly } | |||
13395 | #include "clang/Basic/OperatorKinds.def" | |||
13396 | }; | |||
13397 | ||||
13398 | bool CanBeUnaryOperator = OperatorUses[Op][0]; | |||
13399 | bool CanBeBinaryOperator = OperatorUses[Op][1]; | |||
13400 | bool MustBeMemberOperator = OperatorUses[Op][2]; | |||
13401 | ||||
13402 | // C++ [over.oper]p8: | |||
13403 | // [...] Operator functions cannot have more or fewer parameters | |||
13404 | // than the number required for the corresponding operator, as | |||
13405 | // described in the rest of this subclause. | |||
13406 | unsigned NumParams = FnDecl->getNumParams() | |||
13407 | + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); | |||
13408 | if (Op != OO_Call && | |||
13409 | ((NumParams == 1 && !CanBeUnaryOperator) || | |||
13410 | (NumParams == 2 && !CanBeBinaryOperator) || | |||
13411 | (NumParams < 1) || (NumParams > 2))) { | |||
13412 | // We have the wrong number of parameters. | |||
13413 | unsigned ErrorKind; | |||
13414 | if (CanBeUnaryOperator && CanBeBinaryOperator) { | |||
13415 | ErrorKind = 2; // 2 -> unary or binary. | |||
13416 | } else if (CanBeUnaryOperator) { | |||
13417 | ErrorKind = 0; // 0 -> unary | |||
13418 | } else { | |||
13419 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13420, __PRETTY_FUNCTION__)) | |||
13420 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13420, __PRETTY_FUNCTION__)); | |||
13421 | ErrorKind = 1; // 1 -> binary | |||
13422 | } | |||
13423 | ||||
13424 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) | |||
13425 | << FnDecl->getDeclName() << NumParams << ErrorKind; | |||
13426 | } | |||
13427 | ||||
13428 | // Overloaded operators other than operator() cannot be variadic. | |||
13429 | if (Op != OO_Call && | |||
13430 | FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { | |||
13431 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) | |||
13432 | << FnDecl->getDeclName(); | |||
13433 | } | |||
13434 | ||||
13435 | // Some operators must be non-static member functions. | |||
13436 | if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { | |||
13437 | return Diag(FnDecl->getLocation(), | |||
13438 | diag::err_operator_overload_must_be_member) | |||
13439 | << FnDecl->getDeclName(); | |||
13440 | } | |||
13441 | ||||
13442 | // C++ [over.inc]p1: | |||
13443 | // The user-defined function called operator++ implements the | |||
13444 | // prefix and postfix ++ operator. If this function is a member | |||
13445 | // function with no parameters, or a non-member function with one | |||
13446 | // parameter of class or enumeration type, it defines the prefix | |||
13447 | // increment operator ++ for objects of that type. If the function | |||
13448 | // is a member function with one parameter (which shall be of type | |||
13449 | // int) or a non-member function with two parameters (the second | |||
13450 | // of which shall be of type int), it defines the postfix | |||
13451 | // increment operator ++ for objects of that type. | |||
13452 | if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { | |||
13453 | ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); | |||
13454 | QualType ParamType = LastParam->getType(); | |||
13455 | ||||
13456 | if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && | |||
13457 | !ParamType->isDependentType()) | |||
13458 | return Diag(LastParam->getLocation(), | |||
13459 | diag::err_operator_overload_post_incdec_must_be_int) | |||
13460 | << LastParam->getType() << (Op == OO_MinusMinus); | |||
13461 | } | |||
13462 | ||||
13463 | return false; | |||
13464 | } | |||
13465 | ||||
13466 | static bool | |||
13467 | checkLiteralOperatorTemplateParameterList(Sema &SemaRef, | |||
13468 | FunctionTemplateDecl *TpDecl) { | |||
13469 | TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); | |||
13470 | ||||
13471 | // Must have one or two template parameters. | |||
13472 | if (TemplateParams->size() == 1) { | |||
13473 | NonTypeTemplateParmDecl *PmDecl = | |||
13474 | dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); | |||
13475 | ||||
13476 | // The template parameter must be a char parameter pack. | |||
13477 | if (PmDecl && PmDecl->isTemplateParameterPack() && | |||
13478 | SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) | |||
13479 | return false; | |||
13480 | ||||
13481 | } else if (TemplateParams->size() == 2) { | |||
13482 | TemplateTypeParmDecl *PmType = | |||
13483 | dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); | |||
13484 | NonTypeTemplateParmDecl *PmArgs = | |||
13485 | dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); | |||
13486 | ||||
13487 | // The second template parameter must be a parameter pack with the | |||
13488 | // first template parameter as its type. | |||
13489 | if (PmType && PmArgs && !PmType->isTemplateParameterPack() && | |||
13490 | PmArgs->isTemplateParameterPack()) { | |||
13491 | const TemplateTypeParmType *TArgs = | |||
13492 | PmArgs->getType()->getAs<TemplateTypeParmType>(); | |||
13493 | if (TArgs && TArgs->getDepth() == PmType->getDepth() && | |||
13494 | TArgs->getIndex() == PmType->getIndex()) { | |||
13495 | if (!SemaRef.inTemplateInstantiation()) | |||
13496 | SemaRef.Diag(TpDecl->getLocation(), | |||
13497 | diag::ext_string_literal_operator_template); | |||
13498 | return false; | |||
13499 | } | |||
13500 | } | |||
13501 | } | |||
13502 | ||||
13503 | SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), | |||
13504 | diag::err_literal_operator_template) | |||
13505 | << TpDecl->getTemplateParameters()->getSourceRange(); | |||
13506 | return true; | |||
13507 | } | |||
13508 | ||||
13509 | /// CheckLiteralOperatorDeclaration - Check whether the declaration | |||
13510 | /// of this literal operator function is well-formed. If so, returns | |||
13511 | /// false; otherwise, emits appropriate diagnostics and returns true. | |||
13512 | bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { | |||
13513 | if (isa<CXXMethodDecl>(FnDecl)) { | |||
13514 | Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) | |||
13515 | << FnDecl->getDeclName(); | |||
13516 | return true; | |||
13517 | } | |||
13518 | ||||
13519 | if (FnDecl->isExternC()) { | |||
13520 | Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); | |||
13521 | if (const LinkageSpecDecl *LSD = | |||
13522 | FnDecl->getDeclContext()->getExternCContext()) | |||
13523 | Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); | |||
13524 | return true; | |||
13525 | } | |||
13526 | ||||
13527 | // This might be the definition of a literal operator template. | |||
13528 | FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); | |||
13529 | ||||
13530 | // This might be a specialization of a literal operator template. | |||
13531 | if (!TpDecl) | |||
13532 | TpDecl = FnDecl->getPrimaryTemplate(); | |||
13533 | ||||
13534 | // template <char...> type operator "" name() and | |||
13535 | // template <class T, T...> type operator "" name() are the only valid | |||
13536 | // template signatures, and the only valid signatures with no parameters. | |||
13537 | if (TpDecl) { | |||
13538 | if (FnDecl->param_size() != 0) { | |||
13539 | Diag(FnDecl->getLocation(), | |||
13540 | diag::err_literal_operator_template_with_params); | |||
13541 | return true; | |||
13542 | } | |||
13543 | ||||
13544 | if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) | |||
13545 | return true; | |||
13546 | ||||
13547 | } else if (FnDecl->param_size() == 1) { | |||
13548 | const ParmVarDecl *Param = FnDecl->getParamDecl(0); | |||
13549 | ||||
13550 | QualType ParamType = Param->getType().getUnqualifiedType(); | |||
13551 | ||||
13552 | // Only unsigned long long int, long double, any character type, and const | |||
13553 | // char * are allowed as the only parameters. | |||
13554 | if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || | |||
13555 | ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || | |||
13556 | Context.hasSameType(ParamType, Context.CharTy) || | |||
13557 | Context.hasSameType(ParamType, Context.WideCharTy) || | |||
13558 | Context.hasSameType(ParamType, Context.Char8Ty) || | |||
13559 | Context.hasSameType(ParamType, Context.Char16Ty) || | |||
13560 | Context.hasSameType(ParamType, Context.Char32Ty)) { | |||
13561 | } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { | |||
13562 | QualType InnerType = Ptr->getPointeeType(); | |||
13563 | ||||
13564 | // Pointer parameter must be a const char *. | |||
13565 | if (!(Context.hasSameType(InnerType.getUnqualifiedType(), | |||
13566 | Context.CharTy) && | |||
13567 | InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { | |||
13568 | Diag(Param->getSourceRange().getBegin(), | |||
13569 | diag::err_literal_operator_param) | |||
13570 | << ParamType << "'const char *'" << Param->getSourceRange(); | |||
13571 | return true; | |||
13572 | } | |||
13573 | ||||
13574 | } else if (ParamType->isRealFloatingType()) { | |||
13575 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) | |||
13576 | << ParamType << Context.LongDoubleTy << Param->getSourceRange(); | |||
13577 | return true; | |||
13578 | ||||
13579 | } else if (ParamType->isIntegerType()) { | |||
13580 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) | |||
13581 | << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); | |||
13582 | return true; | |||
13583 | ||||
13584 | } else { | |||
13585 | Diag(Param->getSourceRange().getBegin(), | |||
13586 | diag::err_literal_operator_invalid_param) | |||
13587 | << ParamType << Param->getSourceRange(); | |||
13588 | return true; | |||
13589 | } | |||
13590 | ||||
13591 | } else if (FnDecl->param_size() == 2) { | |||
13592 | FunctionDecl::param_iterator Param = FnDecl->param_begin(); | |||
13593 | ||||
13594 | // First, verify that the first parameter is correct. | |||
13595 | ||||
13596 | QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); | |||
13597 | ||||
13598 | // Two parameter function must have a pointer to const as a | |||
13599 | // first parameter; let's strip those qualifiers. | |||
13600 | const PointerType *PT = FirstParamType->getAs<PointerType>(); | |||
13601 | ||||
13602 | if (!PT) { | |||
13603 | Diag((*Param)->getSourceRange().getBegin(), | |||
13604 | diag::err_literal_operator_param) | |||
13605 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | |||
13606 | return true; | |||
13607 | } | |||
13608 | ||||
13609 | QualType PointeeType = PT->getPointeeType(); | |||
13610 | // First parameter must be const | |||
13611 | if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { | |||
13612 | Diag((*Param)->getSourceRange().getBegin(), | |||
13613 | diag::err_literal_operator_param) | |||
13614 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | |||
13615 | return true; | |||
13616 | } | |||
13617 | ||||
13618 | QualType InnerType = PointeeType.getUnqualifiedType(); | |||
13619 | // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and | |||
13620 | // const char32_t* are allowed as the first parameter to a two-parameter | |||
13621 | // function | |||
13622 | if (!(Context.hasSameType(InnerType, Context.CharTy) || | |||
13623 | Context.hasSameType(InnerType, Context.WideCharTy) || | |||
13624 | Context.hasSameType(InnerType, Context.Char8Ty) || | |||
13625 | Context.hasSameType(InnerType, Context.Char16Ty) || | |||
13626 | Context.hasSameType(InnerType, Context.Char32Ty))) { | |||
13627 | Diag((*Param)->getSourceRange().getBegin(), | |||
13628 | diag::err_literal_operator_param) | |||
13629 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | |||
13630 | return true; | |||
13631 | } | |||
13632 | ||||
13633 | // Move on to the second and final parameter. | |||
13634 | ++Param; | |||
13635 | ||||
13636 | // The second parameter must be a std::size_t. | |||
13637 | QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); | |||
13638 | if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { | |||
13639 | Diag((*Param)->getSourceRange().getBegin(), | |||
13640 | diag::err_literal_operator_param) | |||
13641 | << SecondParamType << Context.getSizeType() | |||
13642 | << (*Param)->getSourceRange(); | |||
13643 | return true; | |||
13644 | } | |||
13645 | } else { | |||
13646 | Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); | |||
13647 | return true; | |||
13648 | } | |||
13649 | ||||
13650 | // Parameters are good. | |||
13651 | ||||
13652 | // A parameter-declaration-clause containing a default argument is not | |||
13653 | // equivalent to any of the permitted forms. | |||
13654 | for (auto Param : FnDecl->parameters()) { | |||
13655 | if (Param->hasDefaultArg()) { | |||
13656 | Diag(Param->getDefaultArgRange().getBegin(), | |||
13657 | diag::err_literal_operator_default_argument) | |||
13658 | << Param->getDefaultArgRange(); | |||
13659 | break; | |||
13660 | } | |||
13661 | } | |||
13662 | ||||
13663 | StringRef LiteralName | |||
13664 | = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); | |||
13665 | if (LiteralName[0] != '_' && | |||
13666 | !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { | |||
13667 | // C++11 [usrlit.suffix]p1: | |||
13668 | // Literal suffix identifiers that do not start with an underscore | |||
13669 | // are reserved for future standardization. | |||
13670 | Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) | |||
13671 | << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); | |||
13672 | } | |||
13673 | ||||
13674 | return false; | |||
13675 | } | |||
13676 | ||||
13677 | /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ | |||
13678 | /// linkage specification, including the language and (if present) | |||
13679 | /// the '{'. ExternLoc is the location of the 'extern', Lang is the | |||
13680 | /// language string literal. LBraceLoc, if valid, provides the location of | |||
13681 | /// the '{' brace. Otherwise, this linkage specification does not | |||
13682 | /// have any braces. | |||
13683 | Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, | |||
13684 | Expr *LangStr, | |||
13685 | SourceLocation LBraceLoc) { | |||
13686 | StringLiteral *Lit = cast<StringLiteral>(LangStr); | |||
13687 | if (!Lit->isAscii()) { | |||
13688 | Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) | |||
13689 | << LangStr->getSourceRange(); | |||
13690 | return nullptr; | |||
13691 | } | |||
13692 | ||||
13693 | StringRef Lang = Lit->getString(); | |||
13694 | LinkageSpecDecl::LanguageIDs Language; | |||
13695 | if (Lang == "C") | |||
13696 | Language = LinkageSpecDecl::lang_c; | |||
13697 | else if (Lang == "C++") | |||
13698 | Language = LinkageSpecDecl::lang_cxx; | |||
13699 | else { | |||
13700 | Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) | |||
13701 | << LangStr->getSourceRange(); | |||
13702 | return nullptr; | |||
13703 | } | |||
13704 | ||||
13705 | // FIXME: Add all the various semantics of linkage specifications | |||
13706 | ||||
13707 | LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, | |||
13708 | LangStr->getExprLoc(), Language, | |||
13709 | LBraceLoc.isValid()); | |||
13710 | CurContext->addDecl(D); | |||
13711 | PushDeclContext(S, D); | |||
13712 | return D; | |||
13713 | } | |||
13714 | ||||
13715 | /// ActOnFinishLinkageSpecification - Complete the definition of | |||
13716 | /// the C++ linkage specification LinkageSpec. If RBraceLoc is | |||
13717 | /// valid, it's the position of the closing '}' brace in a linkage | |||
13718 | /// specification that uses braces. | |||
13719 | Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, | |||
13720 | Decl *LinkageSpec, | |||
13721 | SourceLocation RBraceLoc) { | |||
13722 | if (RBraceLoc.isValid()) { | |||
13723 | LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); | |||
13724 | LSDecl->setRBraceLoc(RBraceLoc); | |||
13725 | } | |||
13726 | PopDeclContext(); | |||
13727 | return LinkageSpec; | |||
13728 | } | |||
13729 | ||||
13730 | Decl *Sema::ActOnEmptyDeclaration(Scope *S, | |||
13731 | const ParsedAttributesView &AttrList, | |||
13732 | SourceLocation SemiLoc) { | |||
13733 | Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); | |||
13734 | // Attribute declarations appertain to empty declaration so we handle | |||
13735 | // them here. | |||
13736 | ProcessDeclAttributeList(S, ED, AttrList); | |||
13737 | ||||
13738 | CurContext->addDecl(ED); | |||
13739 | return ED; | |||
13740 | } | |||
13741 | ||||
13742 | /// Perform semantic analysis for the variable declaration that | |||
13743 | /// occurs within a C++ catch clause, returning the newly-created | |||
13744 | /// variable. | |||
13745 | VarDecl *Sema::BuildExceptionDeclaration(Scope *S, | |||
13746 | TypeSourceInfo *TInfo, | |||
13747 | SourceLocation StartLoc, | |||
13748 | SourceLocation Loc, | |||
13749 | IdentifierInfo *Name) { | |||
13750 | bool Invalid = false; | |||
13751 | QualType ExDeclType = TInfo->getType(); | |||
13752 | ||||
13753 | // Arrays and functions decay. | |||
13754 | if (ExDeclType->isArrayType()) | |||
13755 | ExDeclType = Context.getArrayDecayedType(ExDeclType); | |||
13756 | else if (ExDeclType->isFunctionType()) | |||
13757 | ExDeclType = Context.getPointerType(ExDeclType); | |||
13758 | ||||
13759 | // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. | |||
13760 | // The exception-declaration shall not denote a pointer or reference to an | |||
13761 | // incomplete type, other than [cv] void*. | |||
13762 | // N2844 forbids rvalue references. | |||
13763 | if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { | |||
13764 | Diag(Loc, diag::err_catch_rvalue_ref); | |||
13765 | Invalid = true; | |||
13766 | } | |||
13767 | ||||
13768 | if (ExDeclType->isVariablyModifiedType()) { | |||
13769 | Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; | |||
13770 | Invalid = true; | |||
13771 | } | |||
13772 | ||||
13773 | QualType BaseType = ExDeclType; | |||
13774 | int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference | |||
13775 | unsigned DK = diag::err_catch_incomplete; | |||
13776 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { | |||
13777 | BaseType = Ptr->getPointeeType(); | |||
13778 | Mode = 1; | |||
13779 | DK = diag::err_catch_incomplete_ptr; | |||
13780 | } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { | |||
13781 | // For the purpose of error recovery, we treat rvalue refs like lvalue refs. | |||
13782 | BaseType = Ref->getPointeeType(); | |||
13783 | Mode = 2; | |||
13784 | DK = diag::err_catch_incomplete_ref; | |||
13785 | } | |||
13786 | if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && | |||
13787 | !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) | |||
13788 | Invalid = true; | |||
13789 | ||||
13790 | if (!Invalid && !ExDeclType->isDependentType() && | |||
13791 | RequireNonAbstractType(Loc, ExDeclType, | |||
13792 | diag::err_abstract_type_in_decl, | |||
13793 | AbstractVariableType)) | |||
13794 | Invalid = true; | |||
13795 | ||||
13796 | // Only the non-fragile NeXT runtime currently supports C++ catches | |||
13797 | // of ObjC types, and no runtime supports catching ObjC types by value. | |||
13798 | if (!Invalid && getLangOpts().ObjC) { | |||
13799 | QualType T = ExDeclType; | |||
13800 | if (const ReferenceType *RT = T->getAs<ReferenceType>()) | |||
13801 | T = RT->getPointeeType(); | |||
13802 | ||||
13803 | if (T->isObjCObjectType()) { | |||
13804 | Diag(Loc, diag::err_objc_object_catch); | |||
13805 | Invalid = true; | |||
13806 | } else if (T->isObjCObjectPointerType()) { | |||
13807 | // FIXME: should this be a test for macosx-fragile specifically? | |||
13808 | if (getLangOpts().ObjCRuntime.isFragile()) | |||
13809 | Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); | |||
13810 | } | |||
13811 | } | |||
13812 | ||||
13813 | VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, | |||
13814 | ExDeclType, TInfo, SC_None); | |||
13815 | ExDecl->setExceptionVariable(true); | |||
13816 | ||||
13817 | // In ARC, infer 'retaining' for variables of retainable type. | |||
13818 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) | |||
13819 | Invalid = true; | |||
13820 | ||||
13821 | if (!Invalid && !ExDeclType->isDependentType()) { | |||
13822 | if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { | |||
13823 | // Insulate this from anything else we might currently be parsing. | |||
13824 | EnterExpressionEvaluationContext scope( | |||
13825 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | |||
13826 | ||||
13827 | // C++ [except.handle]p16: | |||
13828 | // The object declared in an exception-declaration or, if the | |||
13829 | // exception-declaration does not specify a name, a temporary (12.2) is | |||
13830 | // copy-initialized (8.5) from the exception object. [...] | |||
13831 | // The object is destroyed when the handler exits, after the destruction | |||
13832 | // of any automatic objects initialized within the handler. | |||
13833 | // | |||
13834 | // We just pretend to initialize the object with itself, then make sure | |||
13835 | // it can be destroyed later. | |||
13836 | QualType initType = Context.getExceptionObjectType(ExDeclType); | |||
13837 | ||||
13838 | InitializedEntity entity = | |||
13839 | InitializedEntity::InitializeVariable(ExDecl); | |||
13840 | InitializationKind initKind = | |||
13841 | InitializationKind::CreateCopy(Loc, SourceLocation()); | |||
13842 | ||||
13843 | Expr *opaqueValue = | |||
13844 | new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); | |||
13845 | InitializationSequence sequence(*this, entity, initKind, opaqueValue); | |||
13846 | ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); | |||
13847 | if (result.isInvalid()) | |||
13848 | Invalid = true; | |||
13849 | else { | |||
13850 | // If the constructor used was non-trivial, set this as the | |||
13851 | // "initializer". | |||
13852 | CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); | |||
13853 | if (!construct->getConstructor()->isTrivial()) { | |||
13854 | Expr *init = MaybeCreateExprWithCleanups(construct); | |||
13855 | ExDecl->setInit(init); | |||
13856 | } | |||
13857 | ||||
13858 | // And make sure it's destructable. | |||
13859 | FinalizeVarWithDestructor(ExDecl, recordType); | |||
13860 | } | |||
13861 | } | |||
13862 | } | |||
13863 | ||||
13864 | if (Invalid) | |||
13865 | ExDecl->setInvalidDecl(); | |||
13866 | ||||
13867 | return ExDecl; | |||
13868 | } | |||
13869 | ||||
13870 | /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch | |||
13871 | /// handler. | |||
13872 | Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { | |||
13873 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
13874 | bool Invalid = D.isInvalidType(); | |||
13875 | ||||
13876 | // Check for unexpanded parameter packs. | |||
13877 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
13878 | UPPC_ExceptionType)) { | |||
13879 | TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, | |||
13880 | D.getIdentifierLoc()); | |||
13881 | Invalid = true; | |||
13882 | } | |||
13883 | ||||
13884 | IdentifierInfo *II = D.getIdentifier(); | |||
13885 | if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), | |||
13886 | LookupOrdinaryName, | |||
13887 | ForVisibleRedeclaration)) { | |||
13888 | // The scope should be freshly made just for us. There is just no way | |||
13889 | // it contains any previous declaration, except for function parameters in | |||
13890 | // a function-try-block's catch statement. | |||
13891 | assert(!S->isDeclScope(PrevDecl))((!S->isDeclScope(PrevDecl)) ? static_cast<void> (0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13891, __PRETTY_FUNCTION__)); | |||
13892 | if (isDeclInScope(PrevDecl, CurContext, S)) { | |||
13893 | Diag(D.getIdentifierLoc(), diag::err_redefinition) | |||
13894 | << D.getIdentifier(); | |||
13895 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
13896 | Invalid = true; | |||
13897 | } else if (PrevDecl->isTemplateParameter()) | |||
13898 | // Maybe we will complain about the shadowed template parameter. | |||
13899 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
13900 | } | |||
13901 | ||||
13902 | if (D.getCXXScopeSpec().isSet() && !Invalid) { | |||
13903 | Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) | |||
13904 | << D.getCXXScopeSpec().getRange(); | |||
13905 | Invalid = true; | |||
13906 | } | |||
13907 | ||||
13908 | VarDecl *ExDecl = BuildExceptionDeclaration( | |||
13909 | S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); | |||
13910 | if (Invalid) | |||
13911 | ExDecl->setInvalidDecl(); | |||
13912 | ||||
13913 | // Add the exception declaration into this scope. | |||
13914 | if (II) | |||
13915 | PushOnScopeChains(ExDecl, S); | |||
13916 | else | |||
13917 | CurContext->addDecl(ExDecl); | |||
13918 | ||||
13919 | ProcessDeclAttributes(S, ExDecl, D); | |||
13920 | return ExDecl; | |||
13921 | } | |||
13922 | ||||
13923 | Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, | |||
13924 | Expr *AssertExpr, | |||
13925 | Expr *AssertMessageExpr, | |||
13926 | SourceLocation RParenLoc) { | |||
13927 | StringLiteral *AssertMessage = | |||
13928 | AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; | |||
13929 | ||||
13930 | if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) | |||
13931 | return nullptr; | |||
13932 | ||||
13933 | return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, | |||
13934 | AssertMessage, RParenLoc, false); | |||
13935 | } | |||
13936 | ||||
13937 | Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, | |||
13938 | Expr *AssertExpr, | |||
13939 | StringLiteral *AssertMessage, | |||
13940 | SourceLocation RParenLoc, | |||
13941 | bool Failed) { | |||
13942 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 13942, __PRETTY_FUNCTION__)); | |||
13943 | if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && | |||
13944 | !Failed) { | |||
13945 | // In a static_assert-declaration, the constant-expression shall be a | |||
13946 | // constant expression that can be contextually converted to bool. | |||
13947 | ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); | |||
13948 | if (Converted.isInvalid()) | |||
13949 | Failed = true; | |||
13950 | else | |||
13951 | Converted = ConstantExpr::Create(Context, Converted.get()); | |||
13952 | ||||
13953 | llvm::APSInt Cond; | |||
13954 | if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, | |||
13955 | diag::err_static_assert_expression_is_not_constant, | |||
13956 | /*AllowFold=*/false).isInvalid()) | |||
13957 | Failed = true; | |||
13958 | ||||
13959 | if (!Failed && !Cond) { | |||
13960 | SmallString<256> MsgBuffer; | |||
13961 | llvm::raw_svector_ostream Msg(MsgBuffer); | |||
13962 | if (AssertMessage) | |||
13963 | AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); | |||
13964 | ||||
13965 | Expr *InnerCond = nullptr; | |||
13966 | std::string InnerCondDescription; | |||
13967 | std::tie(InnerCond, InnerCondDescription) = | |||
13968 | findFailedBooleanCondition(Converted.get()); | |||
13969 | if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) | |||
13970 | && !isa<IntegerLiteral>(InnerCond)) { | |||
13971 | Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) | |||
13972 | << InnerCondDescription << !AssertMessage | |||
13973 | << Msg.str() << InnerCond->getSourceRange(); | |||
13974 | } else { | |||
13975 | Diag(StaticAssertLoc, diag::err_static_assert_failed) | |||
13976 | << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); | |||
13977 | } | |||
13978 | Failed = true; | |||
13979 | } | |||
13980 | } | |||
13981 | ||||
13982 | ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, | |||
13983 | /*DiscardedValue*/false, | |||
13984 | /*IsConstexpr*/true); | |||
13985 | if (FullAssertExpr.isInvalid()) | |||
13986 | Failed = true; | |||
13987 | else | |||
13988 | AssertExpr = FullAssertExpr.get(); | |||
13989 | ||||
13990 | Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, | |||
13991 | AssertExpr, AssertMessage, RParenLoc, | |||
13992 | Failed); | |||
13993 | ||||
13994 | CurContext->addDecl(Decl); | |||
13995 | return Decl; | |||
13996 | } | |||
13997 | ||||
13998 | /// Perform semantic analysis of the given friend type declaration. | |||
13999 | /// | |||
14000 | /// \returns A friend declaration that. | |||
14001 | FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, | |||
14002 | SourceLocation FriendLoc, | |||
14003 | TypeSourceInfo *TSInfo) { | |||
14004 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14004, __PRETTY_FUNCTION__)); | |||
14005 | ||||
14006 | QualType T = TSInfo->getType(); | |||
14007 | SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); | |||
14008 | ||||
14009 | // C++03 [class.friend]p2: | |||
14010 | // An elaborated-type-specifier shall be used in a friend declaration | |||
14011 | // for a class.* | |||
14012 | // | |||
14013 | // * The class-key of the elaborated-type-specifier is required. | |||
14014 | if (!CodeSynthesisContexts.empty()) { | |||
14015 | // Do not complain about the form of friend template types during any kind | |||
14016 | // of code synthesis. For template instantiation, we will have complained | |||
14017 | // when the template was defined. | |||
14018 | } else { | |||
14019 | if (!T->isElaboratedTypeSpecifier()) { | |||
14020 | // If we evaluated the type to a record type, suggest putting | |||
14021 | // a tag in front. | |||
14022 | if (const RecordType *RT = T->getAs<RecordType>()) { | |||
14023 | RecordDecl *RD = RT->getDecl(); | |||
14024 | ||||
14025 | SmallString<16> InsertionText(" "); | |||
14026 | InsertionText += RD->getKindName(); | |||
14027 | ||||
14028 | Diag(TypeRange.getBegin(), | |||
14029 | getLangOpts().CPlusPlus11 ? | |||
14030 | diag::warn_cxx98_compat_unelaborated_friend_type : | |||
14031 | diag::ext_unelaborated_friend_type) | |||
14032 | << (unsigned) RD->getTagKind() | |||
14033 | << T | |||
14034 | << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), | |||
14035 | InsertionText); | |||
14036 | } else { | |||
14037 | Diag(FriendLoc, | |||
14038 | getLangOpts().CPlusPlus11 ? | |||
14039 | diag::warn_cxx98_compat_nonclass_type_friend : | |||
14040 | diag::ext_nonclass_type_friend) | |||
14041 | << T | |||
14042 | << TypeRange; | |||
14043 | } | |||
14044 | } else if (T->getAs<EnumType>()) { | |||
14045 | Diag(FriendLoc, | |||
14046 | getLangOpts().CPlusPlus11 ? | |||
14047 | diag::warn_cxx98_compat_enum_friend : | |||
14048 | diag::ext_enum_friend) | |||
14049 | << T | |||
14050 | << TypeRange; | |||
14051 | } | |||
14052 | ||||
14053 | // C++11 [class.friend]p3: | |||
14054 | // A friend declaration that does not declare a function shall have one | |||
14055 | // of the following forms: | |||
14056 | // friend elaborated-type-specifier ; | |||
14057 | // friend simple-type-specifier ; | |||
14058 | // friend typename-specifier ; | |||
14059 | if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) | |||
14060 | Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; | |||
14061 | } | |||
14062 | ||||
14063 | // If the type specifier in a friend declaration designates a (possibly | |||
14064 | // cv-qualified) class type, that class is declared as a friend; otherwise, | |||
14065 | // the friend declaration is ignored. | |||
14066 | return FriendDecl::Create(Context, CurContext, | |||
14067 | TSInfo->getTypeLoc().getBeginLoc(), TSInfo, | |||
14068 | FriendLoc); | |||
14069 | } | |||
14070 | ||||
14071 | /// Handle a friend tag declaration where the scope specifier was | |||
14072 | /// templated. | |||
14073 | Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, | |||
14074 | unsigned TagSpec, SourceLocation TagLoc, | |||
14075 | CXXScopeSpec &SS, IdentifierInfo *Name, | |||
14076 | SourceLocation NameLoc, | |||
14077 | const ParsedAttributesView &Attr, | |||
14078 | MultiTemplateParamsArg TempParamLists) { | |||
14079 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | |||
14080 | ||||
14081 | bool IsMemberSpecialization = false; | |||
14082 | bool Invalid = false; | |||
14083 | ||||
14084 | if (TemplateParameterList *TemplateParams = | |||
14085 | MatchTemplateParametersToScopeSpecifier( | |||
14086 | TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, | |||
14087 | IsMemberSpecialization, Invalid)) { | |||
14088 | if (TemplateParams->size() > 0) { | |||
14089 | // This is a declaration of a class template. | |||
14090 | if (Invalid) | |||
14091 | return nullptr; | |||
14092 | ||||
14093 | return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, | |||
14094 | NameLoc, Attr, TemplateParams, AS_public, | |||
14095 | /*ModulePrivateLoc=*/SourceLocation(), | |||
14096 | FriendLoc, TempParamLists.size() - 1, | |||
14097 | TempParamLists.data()).get(); | |||
14098 | } else { | |||
14099 | // The "template<>" header is extraneous. | |||
14100 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | |||
14101 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | |||
14102 | IsMemberSpecialization = true; | |||
14103 | } | |||
14104 | } | |||
14105 | ||||
14106 | if (Invalid) return nullptr; | |||
14107 | ||||
14108 | bool isAllExplicitSpecializations = true; | |||
14109 | for (unsigned I = TempParamLists.size(); I-- > 0; ) { | |||
14110 | if (TempParamLists[I]->size()) { | |||
14111 | isAllExplicitSpecializations = false; | |||
14112 | break; | |||
14113 | } | |||
14114 | } | |||
14115 | ||||
14116 | // FIXME: don't ignore attributes. | |||
14117 | ||||
14118 | // If it's explicit specializations all the way down, just forget | |||
14119 | // about the template header and build an appropriate non-templated | |||
14120 | // friend. TODO: for source fidelity, remember the headers. | |||
14121 | if (isAllExplicitSpecializations) { | |||
14122 | if (SS.isEmpty()) { | |||
14123 | bool Owned = false; | |||
14124 | bool IsDependent = false; | |||
14125 | return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, | |||
14126 | Attr, AS_public, | |||
14127 | /*ModulePrivateLoc=*/SourceLocation(), | |||
14128 | MultiTemplateParamsArg(), Owned, IsDependent, | |||
14129 | /*ScopedEnumKWLoc=*/SourceLocation(), | |||
14130 | /*ScopedEnumUsesClassTag=*/false, | |||
14131 | /*UnderlyingType=*/TypeResult(), | |||
14132 | /*IsTypeSpecifier=*/false, | |||
14133 | /*IsTemplateParamOrArg=*/false); | |||
14134 | } | |||
14135 | ||||
14136 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); | |||
14137 | ElaboratedTypeKeyword Keyword | |||
14138 | = TypeWithKeyword::getKeywordForTagTypeKind(Kind); | |||
14139 | QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, | |||
14140 | *Name, NameLoc); | |||
14141 | if (T.isNull()) | |||
14142 | return nullptr; | |||
14143 | ||||
14144 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); | |||
14145 | if (isa<DependentNameType>(T)) { | |||
14146 | DependentNameTypeLoc TL = | |||
14147 | TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); | |||
14148 | TL.setElaboratedKeywordLoc(TagLoc); | |||
14149 | TL.setQualifierLoc(QualifierLoc); | |||
14150 | TL.setNameLoc(NameLoc); | |||
14151 | } else { | |||
14152 | ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); | |||
14153 | TL.setElaboratedKeywordLoc(TagLoc); | |||
14154 | TL.setQualifierLoc(QualifierLoc); | |||
14155 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); | |||
14156 | } | |||
14157 | ||||
14158 | FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, | |||
14159 | TSI, FriendLoc, TempParamLists); | |||
14160 | Friend->setAccess(AS_public); | |||
14161 | CurContext->addDecl(Friend); | |||
14162 | return Friend; | |||
14163 | } | |||
14164 | ||||
14165 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14165, __PRETTY_FUNCTION__)); | |||
14166 | ||||
14167 | ||||
14168 | ||||
14169 | // Handle the case of a templated-scope friend class. e.g. | |||
14170 | // template <class T> class A<T>::B; | |||
14171 | // FIXME: we don't support these right now. | |||
14172 | Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) | |||
14173 | << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); | |||
14174 | ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); | |||
14175 | QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); | |||
14176 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); | |||
14177 | DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); | |||
14178 | TL.setElaboratedKeywordLoc(TagLoc); | |||
14179 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
14180 | TL.setNameLoc(NameLoc); | |||
14181 | ||||
14182 | FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, | |||
14183 | TSI, FriendLoc, TempParamLists); | |||
14184 | Friend->setAccess(AS_public); | |||
14185 | Friend->setUnsupportedFriend(true); | |||
14186 | CurContext->addDecl(Friend); | |||
14187 | return Friend; | |||
14188 | } | |||
14189 | ||||
14190 | /// Handle a friend type declaration. This works in tandem with | |||
14191 | /// ActOnTag. | |||
14192 | /// | |||
14193 | /// Notes on friend class templates: | |||
14194 | /// | |||
14195 | /// We generally treat friend class declarations as if they were | |||
14196 | /// declaring a class. So, for example, the elaborated type specifier | |||
14197 | /// in a friend declaration is required to obey the restrictions of a | |||
14198 | /// class-head (i.e. no typedefs in the scope chain), template | |||
14199 | /// parameters are required to match up with simple template-ids, &c. | |||
14200 | /// However, unlike when declaring a template specialization, it's | |||
14201 | /// okay to refer to a template specialization without an empty | |||
14202 | /// template parameter declaration, e.g. | |||
14203 | /// friend class A<T>::B<unsigned>; | |||
14204 | /// We permit this as a special case; if there are any template | |||
14205 | /// parameters present at all, require proper matching, i.e. | |||
14206 | /// template <> template \<class T> friend class A<int>::B; | |||
14207 | Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, | |||
14208 | MultiTemplateParamsArg TempParams) { | |||
14209 | SourceLocation Loc = DS.getBeginLoc(); | |||
14210 | ||||
14211 | assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14211, __PRETTY_FUNCTION__)); | |||
14212 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14212, __PRETTY_FUNCTION__)); | |||
14213 | ||||
14214 | // C++ [class.friend]p3: | |||
14215 | // A friend declaration that does not declare a function shall have one of | |||
14216 | // the following forms: | |||
14217 | // friend elaborated-type-specifier ; | |||
14218 | // friend simple-type-specifier ; | |||
14219 | // friend typename-specifier ; | |||
14220 | // | |||
14221 | // Any declaration with a type qualifier does not have that form. (It's | |||
14222 | // legal to specify a qualified type as a friend, you just can't write the | |||
14223 | // keywords.) | |||
14224 | if (DS.getTypeQualifiers()) { | |||
14225 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | |||
14226 | Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; | |||
14227 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | |||
14228 | Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; | |||
14229 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | |||
14230 | Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; | |||
14231 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | |||
14232 | Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; | |||
14233 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | |||
14234 | Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; | |||
14235 | } | |||
14236 | ||||
14237 | // Try to convert the decl specifier to a type. This works for | |||
14238 | // friend templates because ActOnTag never produces a ClassTemplateDecl | |||
14239 | // for a TUK_Friend. | |||
14240 | Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); | |||
14241 | TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); | |||
14242 | QualType T = TSI->getType(); | |||
14243 | if (TheDeclarator.isInvalidType()) | |||
14244 | return nullptr; | |||
14245 | ||||
14246 | if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) | |||
14247 | return nullptr; | |||
14248 | ||||
14249 | // This is definitely an error in C++98. It's probably meant to | |||
14250 | // be forbidden in C++0x, too, but the specification is just | |||
14251 | // poorly written. | |||
14252 | // | |||
14253 | // The problem is with declarations like the following: | |||
14254 | // template <T> friend A<T>::foo; | |||
14255 | // where deciding whether a class C is a friend or not now hinges | |||
14256 | // on whether there exists an instantiation of A that causes | |||
14257 | // 'foo' to equal C. There are restrictions on class-heads | |||
14258 | // (which we declare (by fiat) elaborated friend declarations to | |||
14259 | // be) that makes this tractable. | |||
14260 | // | |||
14261 | // FIXME: handle "template <> friend class A<T>;", which | |||
14262 | // is possibly well-formed? Who even knows? | |||
14263 | if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { | |||
14264 | Diag(Loc, diag::err_tagless_friend_type_template) | |||
14265 | << DS.getSourceRange(); | |||
14266 | return nullptr; | |||
14267 | } | |||
14268 | ||||
14269 | // C++98 [class.friend]p1: A friend of a class is a function | |||
14270 | // or class that is not a member of the class . . . | |||
14271 | // This is fixed in DR77, which just barely didn't make the C++03 | |||
14272 | // deadline. It's also a very silly restriction that seriously | |||
14273 | // affects inner classes and which nobody else seems to implement; | |||
14274 | // thus we never diagnose it, not even in -pedantic. | |||
14275 | // | |||
14276 | // But note that we could warn about it: it's always useless to | |||
14277 | // friend one of your own members (it's not, however, worthless to | |||
14278 | // friend a member of an arbitrary specialization of your template). | |||
14279 | ||||
14280 | Decl *D; | |||
14281 | if (!TempParams.empty()) | |||
14282 | D = FriendTemplateDecl::Create(Context, CurContext, Loc, | |||
14283 | TempParams, | |||
14284 | TSI, | |||
14285 | DS.getFriendSpecLoc()); | |||
14286 | else | |||
14287 | D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); | |||
14288 | ||||
14289 | if (!D) | |||
14290 | return nullptr; | |||
14291 | ||||
14292 | D->setAccess(AS_public); | |||
14293 | CurContext->addDecl(D); | |||
14294 | ||||
14295 | return D; | |||
14296 | } | |||
14297 | ||||
14298 | NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, | |||
14299 | MultiTemplateParamsArg TemplateParams) { | |||
14300 | const DeclSpec &DS = D.getDeclSpec(); | |||
14301 | ||||
14302 | assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14302, __PRETTY_FUNCTION__)); | |||
14303 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14303, __PRETTY_FUNCTION__)); | |||
14304 | ||||
14305 | SourceLocation Loc = D.getIdentifierLoc(); | |||
14306 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
14307 | ||||
14308 | // C++ [class.friend]p1 | |||
14309 | // A friend of a class is a function or class.... | |||
14310 | // Note that this sees through typedefs, which is intended. | |||
14311 | // It *doesn't* see through dependent types, which is correct | |||
14312 | // according to [temp.arg.type]p3: | |||
14313 | // If a declaration acquires a function type through a | |||
14314 | // type dependent on a template-parameter and this causes | |||
14315 | // a declaration that does not use the syntactic form of a | |||
14316 | // function declarator to have a function type, the program | |||
14317 | // is ill-formed. | |||
14318 | if (!TInfo->getType()->isFunctionType()) { | |||
14319 | Diag(Loc, diag::err_unexpected_friend); | |||
14320 | ||||
14321 | // It might be worthwhile to try to recover by creating an | |||
14322 | // appropriate declaration. | |||
14323 | return nullptr; | |||
14324 | } | |||
14325 | ||||
14326 | // C++ [namespace.memdef]p3 | |||
14327 | // - If a friend declaration in a non-local class first declares a | |||
14328 | // class or function, the friend class or function is a member | |||
14329 | // of the innermost enclosing namespace. | |||
14330 | // - The name of the friend is not found by simple name lookup | |||
14331 | // until a matching declaration is provided in that namespace | |||
14332 | // scope (either before or after the class declaration granting | |||
14333 | // friendship). | |||
14334 | // - If a friend function is called, its name may be found by the | |||
14335 | // name lookup that considers functions from namespaces and | |||
14336 | // classes associated with the types of the function arguments. | |||
14337 | // - When looking for a prior declaration of a class or a function | |||
14338 | // declared as a friend, scopes outside the innermost enclosing | |||
14339 | // namespace scope are not considered. | |||
14340 | ||||
14341 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | |||
14342 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
14343 | assert(NameInfo.getName())((NameInfo.getName()) ? static_cast<void> (0) : __assert_fail ("NameInfo.getName()", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14343, __PRETTY_FUNCTION__)); | |||
14344 | ||||
14345 | // Check for unexpanded parameter packs. | |||
14346 | if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || | |||
14347 | DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || | |||
14348 | DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) | |||
14349 | return nullptr; | |||
14350 | ||||
14351 | // The context we found the declaration in, or in which we should | |||
14352 | // create the declaration. | |||
14353 | DeclContext *DC; | |||
14354 | Scope *DCScope = S; | |||
14355 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
14356 | ForExternalRedeclaration); | |||
14357 | ||||
14358 | // There are five cases here. | |||
14359 | // - There's no scope specifier and we're in a local class. Only look | |||
14360 | // for functions declared in the immediately-enclosing block scope. | |||
14361 | // We recover from invalid scope qualifiers as if they just weren't there. | |||
14362 | FunctionDecl *FunctionContainingLocalClass = nullptr; | |||
14363 | if ((SS.isInvalid() || !SS.isSet()) && | |||
14364 | (FunctionContainingLocalClass = | |||
14365 | cast<CXXRecordDecl>(CurContext)->isLocalClass())) { | |||
14366 | // C++11 [class.friend]p11: | |||
14367 | // If a friend declaration appears in a local class and the name | |||
14368 | // specified is an unqualified name, a prior declaration is | |||
14369 | // looked up without considering scopes that are outside the | |||
14370 | // innermost enclosing non-class scope. For a friend function | |||
14371 | // declaration, if there is no prior declaration, the program is | |||
14372 | // ill-formed. | |||
14373 | ||||
14374 | // Find the innermost enclosing non-class scope. This is the block | |||
14375 | // scope containing the local class definition (or for a nested class, | |||
14376 | // the outer local class). | |||
14377 | DCScope = S->getFnParent(); | |||
14378 | ||||
14379 | // Look up the function name in the scope. | |||
14380 | Previous.clear(LookupLocalFriendName); | |||
14381 | LookupName(Previous, S, /*AllowBuiltinCreation*/false); | |||
14382 | ||||
14383 | if (!Previous.empty()) { | |||
14384 | // All possible previous declarations must have the same context: | |||
14385 | // either they were declared at block scope or they are members of | |||
14386 | // one of the enclosing local classes. | |||
14387 | DC = Previous.getRepresentativeDecl()->getDeclContext(); | |||
14388 | } else { | |||
14389 | // This is ill-formed, but provide the context that we would have | |||
14390 | // declared the function in, if we were permitted to, for error recovery. | |||
14391 | DC = FunctionContainingLocalClass; | |||
14392 | } | |||
14393 | adjustContextForLocalExternDecl(DC); | |||
14394 | ||||
14395 | // C++ [class.friend]p6: | |||
14396 | // A function can be defined in a friend declaration of a class if and | |||
14397 | // only if the class is a non-local class (9.8), the function name is | |||
14398 | // unqualified, and the function has namespace scope. | |||
14399 | if (D.isFunctionDefinition()) { | |||
14400 | Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); | |||
14401 | } | |||
14402 | ||||
14403 | // - There's no scope specifier, in which case we just go to the | |||
14404 | // appropriate scope and look for a function or function template | |||
14405 | // there as appropriate. | |||
14406 | } else if (SS.isInvalid() || !SS.isSet()) { | |||
14407 | // C++11 [namespace.memdef]p3: | |||
14408 | // If the name in a friend declaration is neither qualified nor | |||
14409 | // a template-id and the declaration is a function or an | |||
14410 | // elaborated-type-specifier, the lookup to determine whether | |||
14411 | // the entity has been previously declared shall not consider | |||
14412 | // any scopes outside the innermost enclosing namespace. | |||
14413 | bool isTemplateId = | |||
14414 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; | |||
14415 | ||||
14416 | // Find the appropriate context according to the above. | |||
14417 | DC = CurContext; | |||
14418 | ||||
14419 | // Skip class contexts. If someone can cite chapter and verse | |||
14420 | // for this behavior, that would be nice --- it's what GCC and | |||
14421 | // EDG do, and it seems like a reasonable intent, but the spec | |||
14422 | // really only says that checks for unqualified existing | |||
14423 | // declarations should stop at the nearest enclosing namespace, | |||
14424 | // not that they should only consider the nearest enclosing | |||
14425 | // namespace. | |||
14426 | while (DC->isRecord()) | |||
14427 | DC = DC->getParent(); | |||
14428 | ||||
14429 | DeclContext *LookupDC = DC; | |||
14430 | while (LookupDC->isTransparentContext()) | |||
14431 | LookupDC = LookupDC->getParent(); | |||
14432 | ||||
14433 | while (true) { | |||
14434 | LookupQualifiedName(Previous, LookupDC); | |||
14435 | ||||
14436 | if (!Previous.empty()) { | |||
14437 | DC = LookupDC; | |||
14438 | break; | |||
14439 | } | |||
14440 | ||||
14441 | if (isTemplateId) { | |||
14442 | if (isa<TranslationUnitDecl>(LookupDC)) break; | |||
14443 | } else { | |||
14444 | if (LookupDC->isFileContext()) break; | |||
14445 | } | |||
14446 | LookupDC = LookupDC->getParent(); | |||
14447 | } | |||
14448 | ||||
14449 | DCScope = getScopeForDeclContext(S, DC); | |||
14450 | ||||
14451 | // - There's a non-dependent scope specifier, in which case we | |||
14452 | // compute it and do a previous lookup there for a function | |||
14453 | // or function template. | |||
14454 | } else if (!SS.getScopeRep()->isDependent()) { | |||
14455 | DC = computeDeclContext(SS); | |||
14456 | if (!DC) return nullptr; | |||
14457 | ||||
14458 | if (RequireCompleteDeclContext(SS, DC)) return nullptr; | |||
14459 | ||||
14460 | LookupQualifiedName(Previous, DC); | |||
14461 | ||||
14462 | // C++ [class.friend]p1: A friend of a class is a function or | |||
14463 | // class that is not a member of the class . . . | |||
14464 | if (DC->Equals(CurContext)) | |||
14465 | Diag(DS.getFriendSpecLoc(), | |||
14466 | getLangOpts().CPlusPlus11 ? | |||
14467 | diag::warn_cxx98_compat_friend_is_member : | |||
14468 | diag::err_friend_is_member); | |||
14469 | ||||
14470 | if (D.isFunctionDefinition()) { | |||
14471 | // C++ [class.friend]p6: | |||
14472 | // A function can be defined in a friend declaration of a class if and | |||
14473 | // only if the class is a non-local class (9.8), the function name is | |||
14474 | // unqualified, and the function has namespace scope. | |||
14475 | // | |||
14476 | // FIXME: We should only do this if the scope specifier names the | |||
14477 | // innermost enclosing namespace; otherwise the fixit changes the | |||
14478 | // meaning of the code. | |||
14479 | SemaDiagnosticBuilder DB | |||
14480 | = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); | |||
14481 | ||||
14482 | DB << SS.getScopeRep(); | |||
14483 | if (DC->isFileContext()) | |||
14484 | DB << FixItHint::CreateRemoval(SS.getRange()); | |||
14485 | SS.clear(); | |||
14486 | } | |||
14487 | ||||
14488 | // - There's a scope specifier that does not match any template | |||
14489 | // parameter lists, in which case we use some arbitrary context, | |||
14490 | // create a method or method template, and wait for instantiation. | |||
14491 | // - There's a scope specifier that does match some template | |||
14492 | // parameter lists, which we don't handle right now. | |||
14493 | } else { | |||
14494 | if (D.isFunctionDefinition()) { | |||
14495 | // C++ [class.friend]p6: | |||
14496 | // A function can be defined in a friend declaration of a class if and | |||
14497 | // only if the class is a non-local class (9.8), the function name is | |||
14498 | // unqualified, and the function has namespace scope. | |||
14499 | Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) | |||
14500 | << SS.getScopeRep(); | |||
14501 | } | |||
14502 | ||||
14503 | DC = CurContext; | |||
14504 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14504, __PRETTY_FUNCTION__)); | |||
14505 | } | |||
14506 | ||||
14507 | if (!DC->isRecord()) { | |||
14508 | int DiagArg = -1; | |||
14509 | switch (D.getName().getKind()) { | |||
14510 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
14511 | case UnqualifiedIdKind::IK_ConstructorName: | |||
14512 | DiagArg = 0; | |||
14513 | break; | |||
14514 | case UnqualifiedIdKind::IK_DestructorName: | |||
14515 | DiagArg = 1; | |||
14516 | break; | |||
14517 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
14518 | DiagArg = 2; | |||
14519 | break; | |||
14520 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
14521 | DiagArg = 3; | |||
14522 | break; | |||
14523 | case UnqualifiedIdKind::IK_Identifier: | |||
14524 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
14525 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
14526 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
14527 | case UnqualifiedIdKind::IK_TemplateId: | |||
14528 | break; | |||
14529 | } | |||
14530 | // This implies that it has to be an operator or function. | |||
14531 | if (DiagArg >= 0) { | |||
14532 | Diag(Loc, diag::err_introducing_special_friend) << DiagArg; | |||
14533 | return nullptr; | |||
14534 | } | |||
14535 | } | |||
14536 | ||||
14537 | // FIXME: This is an egregious hack to cope with cases where the scope stack | |||
14538 | // does not contain the declaration context, i.e., in an out-of-line | |||
14539 | // definition of a class. | |||
14540 | Scope FakeDCScope(S, Scope::DeclScope, Diags); | |||
14541 | if (!DCScope) { | |||
14542 | FakeDCScope.setEntity(DC); | |||
14543 | DCScope = &FakeDCScope; | |||
14544 | } | |||
14545 | ||||
14546 | bool AddToScope = true; | |||
14547 | NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, | |||
14548 | TemplateParams, AddToScope); | |||
14549 | if (!ND) return nullptr; | |||
14550 | ||||
14551 | assert(ND->getLexicalDeclContext() == CurContext)((ND->getLexicalDeclContext() == CurContext) ? static_cast <void> (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14551, __PRETTY_FUNCTION__)); | |||
14552 | ||||
14553 | // If we performed typo correction, we might have added a scope specifier | |||
14554 | // and changed the decl context. | |||
14555 | DC = ND->getDeclContext(); | |||
14556 | ||||
14557 | // Add the function declaration to the appropriate lookup tables, | |||
14558 | // adjusting the redeclarations list as necessary. We don't | |||
14559 | // want to do this yet if the friending class is dependent. | |||
14560 | // | |||
14561 | // Also update the scope-based lookup if the target context's | |||
14562 | // lookup context is in lexical scope. | |||
14563 | if (!CurContext->isDependentContext()) { | |||
14564 | DC = DC->getRedeclContext(); | |||
14565 | DC->makeDeclVisibleInContext(ND); | |||
14566 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | |||
14567 | PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); | |||
14568 | } | |||
14569 | ||||
14570 | FriendDecl *FrD = FriendDecl::Create(Context, CurContext, | |||
14571 | D.getIdentifierLoc(), ND, | |||
14572 | DS.getFriendSpecLoc()); | |||
14573 | FrD->setAccess(AS_public); | |||
14574 | CurContext->addDecl(FrD); | |||
14575 | ||||
14576 | if (ND->isInvalidDecl()) { | |||
14577 | FrD->setInvalidDecl(); | |||
14578 | } else { | |||
14579 | if (DC->isRecord()) CheckFriendAccess(ND); | |||
14580 | ||||
14581 | FunctionDecl *FD; | |||
14582 | if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) | |||
14583 | FD = FTD->getTemplatedDecl(); | |||
14584 | else | |||
14585 | FD = cast<FunctionDecl>(ND); | |||
14586 | ||||
14587 | // C++11 [dcl.fct.default]p4: If a friend declaration specifies a | |||
14588 | // default argument expression, that declaration shall be a definition | |||
14589 | // and shall be the only declaration of the function or function | |||
14590 | // template in the translation unit. | |||
14591 | if (functionDeclHasDefaultArgument(FD)) { | |||
14592 | // We can't look at FD->getPreviousDecl() because it may not have been set | |||
14593 | // if we're in a dependent context. If the function is known to be a | |||
14594 | // redeclaration, we will have narrowed Previous down to the right decl. | |||
14595 | if (D.isRedeclaration()) { | |||
14596 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); | |||
14597 | Diag(Previous.getRepresentativeDecl()->getLocation(), | |||
14598 | diag::note_previous_declaration); | |||
14599 | } else if (!D.isFunctionDefinition()) | |||
14600 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); | |||
14601 | } | |||
14602 | ||||
14603 | // Mark templated-scope function declarations as unsupported. | |||
14604 | if (FD->getNumTemplateParameterLists() && SS.isValid()) { | |||
14605 | Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) | |||
14606 | << SS.getScopeRep() << SS.getRange() | |||
14607 | << cast<CXXRecordDecl>(CurContext); | |||
14608 | FrD->setUnsupportedFriend(true); | |||
14609 | } | |||
14610 | } | |||
14611 | ||||
14612 | return ND; | |||
14613 | } | |||
14614 | ||||
14615 | void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { | |||
14616 | AdjustDeclIfTemplate(Dcl); | |||
14617 | ||||
14618 | FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); | |||
14619 | if (!Fn) { | |||
14620 | Diag(DelLoc, diag::err_deleted_non_function); | |||
14621 | return; | |||
14622 | } | |||
14623 | ||||
14624 | // Deleted function does not have a body. | |||
14625 | Fn->setWillHaveBody(false); | |||
14626 | ||||
14627 | if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { | |||
14628 | // Don't consider the implicit declaration we generate for explicit | |||
14629 | // specializations. FIXME: Do not generate these implicit declarations. | |||
14630 | if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || | |||
14631 | Prev->getPreviousDecl()) && | |||
14632 | !Prev->isDefined()) { | |||
14633 | Diag(DelLoc, diag::err_deleted_decl_not_first); | |||
14634 | Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), | |||
14635 | Prev->isImplicit() ? diag::note_previous_implicit_declaration | |||
14636 | : diag::note_previous_declaration); | |||
14637 | } | |||
14638 | // If the declaration wasn't the first, we delete the function anyway for | |||
14639 | // recovery. | |||
14640 | Fn = Fn->getCanonicalDecl(); | |||
14641 | } | |||
14642 | ||||
14643 | // dllimport/dllexport cannot be deleted. | |||
14644 | if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { | |||
14645 | Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; | |||
14646 | Fn->setInvalidDecl(); | |||
14647 | } | |||
14648 | ||||
14649 | if (Fn->isDeleted()) | |||
14650 | return; | |||
14651 | ||||
14652 | // See if we're deleting a function which is already known to override a | |||
14653 | // non-deleted virtual function. | |||
14654 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { | |||
14655 | bool IssuedDiagnostic = false; | |||
14656 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | |||
14657 | if (!(*MD->begin_overridden_methods())->isDeleted()) { | |||
14658 | if (!IssuedDiagnostic) { | |||
14659 | Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); | |||
14660 | IssuedDiagnostic = true; | |||
14661 | } | |||
14662 | Diag(O->getLocation(), diag::note_overridden_virtual_function); | |||
14663 | } | |||
14664 | } | |||
14665 | // If this function was implicitly deleted because it was defaulted, | |||
14666 | // explain why it was deleted. | |||
14667 | if (IssuedDiagnostic && MD->isDefaulted()) | |||
14668 | ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, | |||
14669 | /*Diagnose*/true); | |||
14670 | } | |||
14671 | ||||
14672 | // C++11 [basic.start.main]p3: | |||
14673 | // A program that defines main as deleted [...] is ill-formed. | |||
14674 | if (Fn->isMain()) | |||
14675 | Diag(DelLoc, diag::err_deleted_main); | |||
14676 | ||||
14677 | // C++11 [dcl.fct.def.delete]p4: | |||
14678 | // A deleted function is implicitly inline. | |||
14679 | Fn->setImplicitlyInline(); | |||
14680 | Fn->setDeletedAsWritten(); | |||
14681 | } | |||
14682 | ||||
14683 | void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { | |||
14684 | CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); | |||
14685 | ||||
14686 | if (MD) { | |||
14687 | if (MD->getParent()->isDependentType()) { | |||
14688 | MD->setDefaulted(); | |||
14689 | MD->setExplicitlyDefaulted(); | |||
14690 | return; | |||
14691 | } | |||
14692 | ||||
14693 | CXXSpecialMember Member = getSpecialMember(MD); | |||
14694 | if (Member == CXXInvalid) { | |||
14695 | if (!MD->isInvalidDecl()) | |||
14696 | Diag(DefaultLoc, diag::err_default_special_members); | |||
14697 | return; | |||
14698 | } | |||
14699 | ||||
14700 | MD->setDefaulted(); | |||
14701 | MD->setExplicitlyDefaulted(); | |||
14702 | ||||
14703 | // Unset that we will have a body for this function. We might not, | |||
14704 | // if it turns out to be trivial, and we don't need this marking now | |||
14705 | // that we've marked it as defaulted. | |||
14706 | MD->setWillHaveBody(false); | |||
14707 | ||||
14708 | // If this definition appears within the record, do the checking when | |||
14709 | // the record is complete. | |||
14710 | const FunctionDecl *Primary = MD; | |||
14711 | if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) | |||
14712 | // Ask the template instantiation pattern that actually had the | |||
14713 | // '= default' on it. | |||
14714 | Primary = Pattern; | |||
14715 | ||||
14716 | // If the method was defaulted on its first declaration, we will have | |||
14717 | // already performed the checking in CheckCompletedCXXClass. Such a | |||
14718 | // declaration doesn't trigger an implicit definition. | |||
14719 | if (Primary->getCanonicalDecl()->isDefaulted()) | |||
14720 | return; | |||
14721 | ||||
14722 | CheckExplicitlyDefaultedSpecialMember(MD); | |||
14723 | ||||
14724 | if (!MD->isInvalidDecl()) | |||
14725 | DefineImplicitSpecialMember(*this, MD, DefaultLoc); | |||
14726 | } else { | |||
14727 | Diag(DefaultLoc, diag::err_default_special_members); | |||
14728 | } | |||
14729 | } | |||
14730 | ||||
14731 | static void SearchForReturnInStmt(Sema &Self, Stmt *S) { | |||
14732 | for (Stmt *SubStmt : S->children()) { | |||
14733 | if (!SubStmt) | |||
14734 | continue; | |||
14735 | if (isa<ReturnStmt>(SubStmt)) | |||
14736 | Self.Diag(SubStmt->getBeginLoc(), | |||
14737 | diag::err_return_in_constructor_handler); | |||
14738 | if (!isa<Expr>(SubStmt)) | |||
14739 | SearchForReturnInStmt(Self, SubStmt); | |||
14740 | } | |||
14741 | } | |||
14742 | ||||
14743 | void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { | |||
14744 | for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { | |||
14745 | CXXCatchStmt *Handler = TryBlock->getHandler(I); | |||
14746 | SearchForReturnInStmt(*this, Handler); | |||
14747 | } | |||
14748 | } | |||
14749 | ||||
14750 | bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, | |||
14751 | const CXXMethodDecl *Old) { | |||
14752 | const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); | |||
14753 | const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); | |||
14754 | ||||
14755 | if (OldFT->hasExtParameterInfos()) { | |||
14756 | for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) | |||
14757 | // A parameter of the overriding method should be annotated with noescape | |||
14758 | // if the corresponding parameter of the overridden method is annotated. | |||
14759 | if (OldFT->getExtParameterInfo(I).isNoEscape() && | |||
14760 | !NewFT->getExtParameterInfo(I).isNoEscape()) { | |||
14761 | Diag(New->getParamDecl(I)->getLocation(), | |||
14762 | diag::warn_overriding_method_missing_noescape); | |||
14763 | Diag(Old->getParamDecl(I)->getLocation(), | |||
14764 | diag::note_overridden_marked_noescape); | |||
14765 | } | |||
14766 | } | |||
14767 | ||||
14768 | // Virtual overrides must have the same code_seg. | |||
14769 | const auto *OldCSA = Old->getAttr<CodeSegAttr>(); | |||
14770 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | |||
14771 | if ((NewCSA || OldCSA) && | |||
14772 | (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { | |||
14773 | Diag(New->getLocation(), diag::err_mismatched_code_seg_override); | |||
14774 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
14775 | return true; | |||
14776 | } | |||
14777 | ||||
14778 | CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); | |||
14779 | ||||
14780 | // If the calling conventions match, everything is fine | |||
14781 | if (NewCC == OldCC) | |||
14782 | return false; | |||
14783 | ||||
14784 | // If the calling conventions mismatch because the new function is static, | |||
14785 | // suppress the calling convention mismatch error; the error about static | |||
14786 | // function override (err_static_overrides_virtual from | |||
14787 | // Sema::CheckFunctionDeclaration) is more clear. | |||
14788 | if (New->getStorageClass() == SC_Static) | |||
14789 | return false; | |||
14790 | ||||
14791 | Diag(New->getLocation(), | |||
14792 | diag::err_conflicting_overriding_cc_attributes) | |||
14793 | << New->getDeclName() << New->getType() << Old->getType(); | |||
14794 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); | |||
14795 | return true; | |||
14796 | } | |||
14797 | ||||
14798 | bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, | |||
14799 | const CXXMethodDecl *Old) { | |||
14800 | QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); | |||
14801 | QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); | |||
14802 | ||||
14803 | if (Context.hasSameType(NewTy, OldTy) || | |||
14804 | NewTy->isDependentType() || OldTy->isDependentType()) | |||
14805 | return false; | |||
14806 | ||||
14807 | // Check if the return types are covariant | |||
14808 | QualType NewClassTy, OldClassTy; | |||
14809 | ||||
14810 | /// Both types must be pointers or references to classes. | |||
14811 | if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { | |||
14812 | if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { | |||
14813 | NewClassTy = NewPT->getPointeeType(); | |||
14814 | OldClassTy = OldPT->getPointeeType(); | |||
14815 | } | |||
14816 | } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { | |||
14817 | if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { | |||
14818 | if (NewRT->getTypeClass() == OldRT->getTypeClass()) { | |||
14819 | NewClassTy = NewRT->getPointeeType(); | |||
14820 | OldClassTy = OldRT->getPointeeType(); | |||
14821 | } | |||
14822 | } | |||
14823 | } | |||
14824 | ||||
14825 | // The return types aren't either both pointers or references to a class type. | |||
14826 | if (NewClassTy.isNull()) { | |||
14827 | Diag(New->getLocation(), | |||
14828 | diag::err_different_return_type_for_overriding_virtual_function) | |||
14829 | << New->getDeclName() << NewTy << OldTy | |||
14830 | << New->getReturnTypeSourceRange(); | |||
14831 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14832 | << Old->getReturnTypeSourceRange(); | |||
14833 | ||||
14834 | return true; | |||
14835 | } | |||
14836 | ||||
14837 | if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { | |||
14838 | // C++14 [class.virtual]p8: | |||
14839 | // If the class type in the covariant return type of D::f differs from | |||
14840 | // that of B::f, the class type in the return type of D::f shall be | |||
14841 | // complete at the point of declaration of D::f or shall be the class | |||
14842 | // type D. | |||
14843 | if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { | |||
14844 | if (!RT->isBeingDefined() && | |||
14845 | RequireCompleteType(New->getLocation(), NewClassTy, | |||
14846 | diag::err_covariant_return_incomplete, | |||
14847 | New->getDeclName())) | |||
14848 | return true; | |||
14849 | } | |||
14850 | ||||
14851 | // Check if the new class derives from the old class. | |||
14852 | if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { | |||
14853 | Diag(New->getLocation(), diag::err_covariant_return_not_derived) | |||
14854 | << New->getDeclName() << NewTy << OldTy | |||
14855 | << New->getReturnTypeSourceRange(); | |||
14856 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14857 | << Old->getReturnTypeSourceRange(); | |||
14858 | return true; | |||
14859 | } | |||
14860 | ||||
14861 | // Check if we the conversion from derived to base is valid. | |||
14862 | if (CheckDerivedToBaseConversion( | |||
14863 | NewClassTy, OldClassTy, | |||
14864 | diag::err_covariant_return_inaccessible_base, | |||
14865 | diag::err_covariant_return_ambiguous_derived_to_base_conv, | |||
14866 | New->getLocation(), New->getReturnTypeSourceRange(), | |||
14867 | New->getDeclName(), nullptr)) { | |||
14868 | // FIXME: this note won't trigger for delayed access control | |||
14869 | // diagnostics, and it's impossible to get an undelayed error | |||
14870 | // here from access control during the original parse because | |||
14871 | // the ParsingDeclSpec/ParsingDeclarator are still in scope. | |||
14872 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14873 | << Old->getReturnTypeSourceRange(); | |||
14874 | return true; | |||
14875 | } | |||
14876 | } | |||
14877 | ||||
14878 | // The qualifiers of the return types must be the same. | |||
14879 | if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { | |||
14880 | Diag(New->getLocation(), | |||
14881 | diag::err_covariant_return_type_different_qualifications) | |||
14882 | << New->getDeclName() << NewTy << OldTy | |||
14883 | << New->getReturnTypeSourceRange(); | |||
14884 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14885 | << Old->getReturnTypeSourceRange(); | |||
14886 | return true; | |||
14887 | } | |||
14888 | ||||
14889 | ||||
14890 | // The new class type must have the same or less qualifiers as the old type. | |||
14891 | if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { | |||
14892 | Diag(New->getLocation(), | |||
14893 | diag::err_covariant_return_type_class_type_more_qualified) | |||
14894 | << New->getDeclName() << NewTy << OldTy | |||
14895 | << New->getReturnTypeSourceRange(); | |||
14896 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | |||
14897 | << Old->getReturnTypeSourceRange(); | |||
14898 | return true; | |||
14899 | } | |||
14900 | ||||
14901 | return false; | |||
14902 | } | |||
14903 | ||||
14904 | /// Mark the given method pure. | |||
14905 | /// | |||
14906 | /// \param Method the method to be marked pure. | |||
14907 | /// | |||
14908 | /// \param InitRange the source range that covers the "0" initializer. | |||
14909 | bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { | |||
14910 | SourceLocation EndLoc = InitRange.getEnd(); | |||
14911 | if (EndLoc.isValid()) | |||
14912 | Method->setRangeEnd(EndLoc); | |||
14913 | ||||
14914 | if (Method->isVirtual() || Method->getParent()->isDependentContext()) { | |||
14915 | Method->setPure(); | |||
14916 | return false; | |||
14917 | } | |||
14918 | ||||
14919 | if (!Method->isInvalidDecl()) | |||
14920 | Diag(Method->getLocation(), diag::err_non_virtual_pure) | |||
14921 | << Method->getDeclName() << InitRange; | |||
14922 | return true; | |||
14923 | } | |||
14924 | ||||
14925 | void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { | |||
14926 | if (D->getFriendObjectKind()) | |||
14927 | Diag(D->getLocation(), diag::err_pure_friend); | |||
14928 | else if (auto *M = dyn_cast<CXXMethodDecl>(D)) | |||
14929 | CheckPureMethod(M, ZeroLoc); | |||
14930 | else | |||
14931 | Diag(D->getLocation(), diag::err_illegal_initializer); | |||
14932 | } | |||
14933 | ||||
14934 | /// Determine whether the given declaration is a global variable or | |||
14935 | /// static data member. | |||
14936 | static bool isNonlocalVariable(const Decl *D) { | |||
14937 | if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) | |||
14938 | return Var->hasGlobalStorage(); | |||
14939 | ||||
14940 | return false; | |||
14941 | } | |||
14942 | ||||
14943 | /// Invoked when we are about to parse an initializer for the declaration | |||
14944 | /// 'Dcl'. | |||
14945 | /// | |||
14946 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a | |||
14947 | /// static data member of class X, names should be looked up in the scope of | |||
14948 | /// class X. If the declaration had a scope specifier, a scope will have | |||
14949 | /// been created and passed in for this purpose. Otherwise, S will be null. | |||
14950 | void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { | |||
14951 | // If there is no declaration, there was an error parsing it. | |||
14952 | if (!D || D->isInvalidDecl()) | |||
14953 | return; | |||
14954 | ||||
14955 | // We will always have a nested name specifier here, but this declaration | |||
14956 | // might not be out of line if the specifier names the current namespace: | |||
14957 | // extern int n; | |||
14958 | // int ::n = 0; | |||
14959 | if (S && D->isOutOfLine()) | |||
14960 | EnterDeclaratorContext(S, D->getDeclContext()); | |||
14961 | ||||
14962 | // If we are parsing the initializer for a static data member, push a | |||
14963 | // new expression evaluation context that is associated with this static | |||
14964 | // data member. | |||
14965 | if (isNonlocalVariable(D)) | |||
14966 | PushExpressionEvaluationContext( | |||
14967 | ExpressionEvaluationContext::PotentiallyEvaluated, D); | |||
14968 | } | |||
14969 | ||||
14970 | /// Invoked after we are finished parsing an initializer for the declaration D. | |||
14971 | void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { | |||
14972 | // If there is no declaration, there was an error parsing it. | |||
14973 | if (!D || D->isInvalidDecl()) | |||
14974 | return; | |||
14975 | ||||
14976 | if (isNonlocalVariable(D)) | |||
14977 | PopExpressionEvaluationContext(); | |||
14978 | ||||
14979 | if (S && D->isOutOfLine()) | |||
14980 | ExitDeclaratorContext(S); | |||
14981 | } | |||
14982 | ||||
14983 | /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a | |||
14984 | /// C++ if/switch/while/for statement. | |||
14985 | /// e.g: "if (int x = f()) {...}" | |||
14986 | DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { | |||
14987 | // C++ 6.4p2: | |||
14988 | // The declarator shall not specify a function or an array. | |||
14989 | // The type-specifier-seq shall not contain typedef and shall not declare a | |||
14990 | // new class or enumeration. | |||
14991 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14992, __PRETTY_FUNCTION__)) | |||
14992 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 14992, __PRETTY_FUNCTION__)); | |||
14993 | ||||
14994 | Decl *Dcl = ActOnDeclarator(S, D); | |||
14995 | if (!Dcl) | |||
14996 | return true; | |||
14997 | ||||
14998 | if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. | |||
14999 | Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) | |||
15000 | << D.getSourceRange(); | |||
15001 | return true; | |||
15002 | } | |||
15003 | ||||
15004 | return Dcl; | |||
15005 | } | |||
15006 | ||||
15007 | void Sema::LoadExternalVTableUses() { | |||
15008 | if (!ExternalSource) | |||
15009 | return; | |||
15010 | ||||
15011 | SmallVector<ExternalVTableUse, 4> VTables; | |||
15012 | ExternalSource->ReadUsedVTables(VTables); | |||
15013 | SmallVector<VTableUse, 4> NewUses; | |||
15014 | for (unsigned I = 0, N = VTables.size(); I != N; ++I) { | |||
15015 | llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos | |||
15016 | = VTablesUsed.find(VTables[I].Record); | |||
15017 | // Even if a definition wasn't required before, it may be required now. | |||
15018 | if (Pos != VTablesUsed.end()) { | |||
15019 | if (!Pos->second && VTables[I].DefinitionRequired) | |||
15020 | Pos->second = true; | |||
15021 | continue; | |||
15022 | } | |||
15023 | ||||
15024 | VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; | |||
15025 | NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); | |||
15026 | } | |||
15027 | ||||
15028 | VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); | |||
15029 | } | |||
15030 | ||||
15031 | void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, | |||
15032 | bool DefinitionRequired) { | |||
15033 | // Ignore any vtable uses in unevaluated operands or for classes that do | |||
15034 | // not have a vtable. | |||
15035 | if (!Class->isDynamicClass() || Class->isDependentContext() || | |||
15036 | CurContext->isDependentContext() || isUnevaluatedContext()) | |||
15037 | return; | |||
15038 | // Do not mark as used if compiling for the device outside of the target | |||
15039 | // region. | |||
15040 | if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && | |||
15041 | !isInOpenMPDeclareTargetContext() && | |||
15042 | !isInOpenMPTargetExecutionDirective()) { | |||
15043 | if (!DefinitionRequired) | |||
15044 | MarkVirtualMembersReferenced(Loc, Class); | |||
15045 | return; | |||
15046 | } | |||
15047 | ||||
15048 | // Try to insert this class into the map. | |||
15049 | LoadExternalVTableUses(); | |||
15050 | Class = Class->getCanonicalDecl(); | |||
15051 | std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> | |||
15052 | Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); | |||
15053 | if (!Pos.second) { | |||
15054 | // If we already had an entry, check to see if we are promoting this vtable | |||
15055 | // to require a definition. If so, we need to reappend to the VTableUses | |||
15056 | // list, since we may have already processed the first entry. | |||
15057 | if (DefinitionRequired && !Pos.first->second) { | |||
15058 | Pos.first->second = true; | |||
15059 | } else { | |||
15060 | // Otherwise, we can early exit. | |||
15061 | return; | |||
15062 | } | |||
15063 | } else { | |||
15064 | // The Microsoft ABI requires that we perform the destructor body | |||
15065 | // checks (i.e. operator delete() lookup) when the vtable is marked used, as | |||
15066 | // the deleting destructor is emitted with the vtable, not with the | |||
15067 | // destructor definition as in the Itanium ABI. | |||
15068 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
15069 | CXXDestructorDecl *DD = Class->getDestructor(); | |||
15070 | if (DD && DD->isVirtual() && !DD->isDeleted()) { | |||
15071 | if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { | |||
15072 | // If this is an out-of-line declaration, marking it referenced will | |||
15073 | // not do anything. Manually call CheckDestructor to look up operator | |||
15074 | // delete(). | |||
15075 | ContextRAII SavedContext(*this, DD); | |||
15076 | CheckDestructor(DD); | |||
15077 | } else { | |||
15078 | MarkFunctionReferenced(Loc, Class->getDestructor()); | |||
15079 | } | |||
15080 | } | |||
15081 | } | |||
15082 | } | |||
15083 | ||||
15084 | // Local classes need to have their virtual members marked | |||
15085 | // immediately. For all other classes, we mark their virtual members | |||
15086 | // at the end of the translation unit. | |||
15087 | if (Class->isLocalClass()) | |||
15088 | MarkVirtualMembersReferenced(Loc, Class); | |||
15089 | else | |||
15090 | VTableUses.push_back(std::make_pair(Class, Loc)); | |||
15091 | } | |||
15092 | ||||
15093 | bool Sema::DefineUsedVTables() { | |||
15094 | LoadExternalVTableUses(); | |||
15095 | if (VTableUses.empty()) | |||
15096 | return false; | |||
15097 | ||||
15098 | // Note: The VTableUses vector could grow as a result of marking | |||
15099 | // the members of a class as "used", so we check the size each | |||
15100 | // time through the loop and prefer indices (which are stable) to | |||
15101 | // iterators (which are not). | |||
15102 | bool DefinedAnything = false; | |||
15103 | for (unsigned I = 0; I != VTableUses.size(); ++I) { | |||
15104 | CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); | |||
15105 | if (!Class) | |||
15106 | continue; | |||
15107 | TemplateSpecializationKind ClassTSK = | |||
15108 | Class->getTemplateSpecializationKind(); | |||
15109 | ||||
15110 | SourceLocation Loc = VTableUses[I].second; | |||
15111 | ||||
15112 | bool DefineVTable = true; | |||
15113 | ||||
15114 | // If this class has a key function, but that key function is | |||
15115 | // defined in another translation unit, we don't need to emit the | |||
15116 | // vtable even though we're using it. | |||
15117 | const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); | |||
15118 | if (KeyFunction && !KeyFunction->hasBody()) { | |||
15119 | // The key function is in another translation unit. | |||
15120 | DefineVTable = false; | |||
15121 | TemplateSpecializationKind TSK = | |||
15122 | KeyFunction->getTemplateSpecializationKind(); | |||
15123 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15125, __PRETTY_FUNCTION__)) | |||
15124 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15125, __PRETTY_FUNCTION__)) | |||
15125 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15125, __PRETTY_FUNCTION__)); | |||
15126 | (void)TSK; | |||
15127 | } else if (!KeyFunction) { | |||
15128 | // If we have a class with no key function that is the subject | |||
15129 | // of an explicit instantiation declaration, suppress the | |||
15130 | // vtable; it will live with the explicit instantiation | |||
15131 | // definition. | |||
15132 | bool IsExplicitInstantiationDeclaration = | |||
15133 | ClassTSK == TSK_ExplicitInstantiationDeclaration; | |||
15134 | for (auto R : Class->redecls()) { | |||
15135 | TemplateSpecializationKind TSK | |||
15136 | = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); | |||
15137 | if (TSK == TSK_ExplicitInstantiationDeclaration) | |||
15138 | IsExplicitInstantiationDeclaration = true; | |||
15139 | else if (TSK == TSK_ExplicitInstantiationDefinition) { | |||
15140 | IsExplicitInstantiationDeclaration = false; | |||
15141 | break; | |||
15142 | } | |||
15143 | } | |||
15144 | ||||
15145 | if (IsExplicitInstantiationDeclaration) | |||
15146 | DefineVTable = false; | |||
15147 | } | |||
15148 | ||||
15149 | // The exception specifications for all virtual members may be needed even | |||
15150 | // if we are not providing an authoritative form of the vtable in this TU. | |||
15151 | // We may choose to emit it available_externally anyway. | |||
15152 | if (!DefineVTable) { | |||
15153 | MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); | |||
15154 | continue; | |||
15155 | } | |||
15156 | ||||
15157 | // Mark all of the virtual members of this class as referenced, so | |||
15158 | // that we can build a vtable. Then, tell the AST consumer that a | |||
15159 | // vtable for this class is required. | |||
15160 | DefinedAnything = true; | |||
15161 | MarkVirtualMembersReferenced(Loc, Class); | |||
15162 | CXXRecordDecl *Canonical = Class->getCanonicalDecl(); | |||
15163 | if (VTablesUsed[Canonical]) | |||
15164 | Consumer.HandleVTable(Class); | |||
15165 | ||||
15166 | // Warn if we're emitting a weak vtable. The vtable will be weak if there is | |||
15167 | // no key function or the key function is inlined. Don't warn in C++ ABIs | |||
15168 | // that lack key functions, since the user won't be able to make one. | |||
15169 | if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && | |||
15170 | Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { | |||
15171 | const FunctionDecl *KeyFunctionDef = nullptr; | |||
15172 | if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && | |||
15173 | KeyFunctionDef->isInlined())) { | |||
15174 | Diag(Class->getLocation(), | |||
15175 | ClassTSK == TSK_ExplicitInstantiationDefinition | |||
15176 | ? diag::warn_weak_template_vtable | |||
15177 | : diag::warn_weak_vtable) | |||
15178 | << Class; | |||
15179 | } | |||
15180 | } | |||
15181 | } | |||
15182 | VTableUses.clear(); | |||
15183 | ||||
15184 | return DefinedAnything; | |||
15185 | } | |||
15186 | ||||
15187 | void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, | |||
15188 | const CXXRecordDecl *RD) { | |||
15189 | for (const auto *I : RD->methods()) | |||
15190 | if (I->isVirtual() && !I->isPure()) | |||
15191 | ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); | |||
15192 | } | |||
15193 | ||||
15194 | void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, | |||
15195 | const CXXRecordDecl *RD) { | |||
15196 | // Mark all functions which will appear in RD's vtable as used. | |||
15197 | CXXFinalOverriderMap FinalOverriders; | |||
15198 | RD->getFinalOverriders(FinalOverriders); | |||
15199 | for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), | |||
15200 | E = FinalOverriders.end(); | |||
15201 | I != E; ++I) { | |||
15202 | for (OverridingMethods::const_iterator OI = I->second.begin(), | |||
15203 | OE = I->second.end(); | |||
15204 | OI != OE; ++OI) { | |||
15205 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15205, __PRETTY_FUNCTION__)); | |||
15206 | CXXMethodDecl *Overrider = OI->second.front().Method; | |||
15207 | ||||
15208 | // C++ [basic.def.odr]p2: | |||
15209 | // [...] A virtual member function is used if it is not pure. [...] | |||
15210 | if (!Overrider->isPure()) | |||
15211 | MarkFunctionReferenced(Loc, Overrider); | |||
15212 | } | |||
15213 | } | |||
15214 | ||||
15215 | // Only classes that have virtual bases need a VTT. | |||
15216 | if (RD->getNumVBases() == 0) | |||
15217 | return; | |||
15218 | ||||
15219 | for (const auto &I : RD->bases()) { | |||
15220 | const CXXRecordDecl *Base = | |||
15221 | cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); | |||
15222 | if (Base->getNumVBases() == 0) | |||
15223 | continue; | |||
15224 | MarkVirtualMembersReferenced(Loc, Base); | |||
15225 | } | |||
15226 | } | |||
15227 | ||||
15228 | /// SetIvarInitializers - This routine builds initialization ASTs for the | |||
15229 | /// Objective-C implementation whose ivars need be initialized. | |||
15230 | void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { | |||
15231 | if (!getLangOpts().CPlusPlus) | |||
15232 | return; | |||
15233 | if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { | |||
15234 | SmallVector<ObjCIvarDecl*, 8> ivars; | |||
15235 | CollectIvarsToConstructOrDestruct(OID, ivars); | |||
15236 | if (ivars.empty()) | |||
15237 | return; | |||
15238 | SmallVector<CXXCtorInitializer*, 32> AllToInit; | |||
15239 | for (unsigned i = 0; i < ivars.size(); i++) { | |||
15240 | FieldDecl *Field = ivars[i]; | |||
15241 | if (Field->isInvalidDecl()) | |||
15242 | continue; | |||
15243 | ||||
15244 | CXXCtorInitializer *Member; | |||
15245 | InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); | |||
15246 | InitializationKind InitKind = | |||
15247 | InitializationKind::CreateDefault(ObjCImplementation->getLocation()); | |||
15248 | ||||
15249 | InitializationSequence InitSeq(*this, InitEntity, InitKind, None); | |||
15250 | ExprResult MemberInit = | |||
15251 | InitSeq.Perform(*this, InitEntity, InitKind, None); | |||
15252 | MemberInit = MaybeCreateExprWithCleanups(MemberInit); | |||
15253 | // Note, MemberInit could actually come back empty if no initialization | |||
15254 | // is required (e.g., because it would call a trivial default constructor) | |||
15255 | if (!MemberInit.get() || MemberInit.isInvalid()) | |||
15256 | continue; | |||
15257 | ||||
15258 | Member = | |||
15259 | new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), | |||
15260 | SourceLocation(), | |||
15261 | MemberInit.getAs<Expr>(), | |||
15262 | SourceLocation()); | |||
15263 | AllToInit.push_back(Member); | |||
15264 | ||||
15265 | // Be sure that the destructor is accessible and is marked as referenced. | |||
15266 | if (const RecordType *RecordTy = | |||
15267 | Context.getBaseElementType(Field->getType()) | |||
15268 | ->getAs<RecordType>()) { | |||
15269 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
15270 | if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { | |||
15271 | MarkFunctionReferenced(Field->getLocation(), Destructor); | |||
15272 | CheckDestructorAccess(Field->getLocation(), Destructor, | |||
15273 | PDiag(diag::err_access_dtor_ivar) | |||
15274 | << Context.getBaseElementType(Field->getType())); | |||
15275 | } | |||
15276 | } | |||
15277 | } | |||
15278 | ObjCImplementation->setIvarInitializers(Context, | |||
15279 | AllToInit.data(), AllToInit.size()); | |||
15280 | } | |||
15281 | } | |||
15282 | ||||
15283 | static | |||
15284 | void DelegatingCycleHelper(CXXConstructorDecl* Ctor, | |||
15285 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, | |||
15286 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, | |||
15287 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, | |||
15288 | Sema &S) { | |||
15289 | if (Ctor->isInvalidDecl()) | |||
15290 | return; | |||
15291 | ||||
15292 | CXXConstructorDecl *Target = Ctor->getTargetConstructor(); | |||
15293 | ||||
15294 | // Target may not be determinable yet, for instance if this is a dependent | |||
15295 | // call in an uninstantiated template. | |||
15296 | if (Target) { | |||
15297 | const FunctionDecl *FNTarget = nullptr; | |||
15298 | (void)Target->hasBody(FNTarget); | |||
15299 | Target = const_cast<CXXConstructorDecl*>( | |||
15300 | cast_or_null<CXXConstructorDecl>(FNTarget)); | |||
15301 | } | |||
15302 | ||||
15303 | CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), | |||
15304 | // Avoid dereferencing a null pointer here. | |||
15305 | *TCanonical = Target? Target->getCanonicalDecl() : nullptr; | |||
15306 | ||||
15307 | if (!Current.insert(Canonical).second) | |||
15308 | return; | |||
15309 | ||||
15310 | // We know that beyond here, we aren't chaining into a cycle. | |||
15311 | if (!Target || !Target->isDelegatingConstructor() || | |||
15312 | Target->isInvalidDecl() || Valid.count(TCanonical)) { | |||
15313 | Valid.insert(Current.begin(), Current.end()); | |||
15314 | Current.clear(); | |||
15315 | // We've hit a cycle. | |||
15316 | } else if (TCanonical == Canonical || Invalid.count(TCanonical) || | |||
15317 | Current.count(TCanonical)) { | |||
15318 | // If we haven't diagnosed this cycle yet, do so now. | |||
15319 | if (!Invalid.count(TCanonical)) { | |||
15320 | S.Diag((*Ctor->init_begin())->getSourceLocation(), | |||
15321 | diag::warn_delegating_ctor_cycle) | |||
15322 | << Ctor; | |||
15323 | ||||
15324 | // Don't add a note for a function delegating directly to itself. | |||
15325 | if (TCanonical != Canonical) | |||
15326 | S.Diag(Target->getLocation(), diag::note_it_delegates_to); | |||
15327 | ||||
15328 | CXXConstructorDecl *C = Target; | |||
15329 | while (C->getCanonicalDecl() != Canonical) { | |||
15330 | const FunctionDecl *FNTarget = nullptr; | |||
15331 | (void)C->getTargetConstructor()->hasBody(FNTarget); | |||
15332 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15332, __PRETTY_FUNCTION__)); | |||
15333 | ||||
15334 | C = const_cast<CXXConstructorDecl*>( | |||
15335 | cast<CXXConstructorDecl>(FNTarget)); | |||
15336 | S.Diag(C->getLocation(), diag::note_which_delegates_to); | |||
15337 | } | |||
15338 | } | |||
15339 | ||||
15340 | Invalid.insert(Current.begin(), Current.end()); | |||
15341 | Current.clear(); | |||
15342 | } else { | |||
15343 | DelegatingCycleHelper(Target, Valid, Invalid, Current, S); | |||
15344 | } | |||
15345 | } | |||
15346 | ||||
15347 | ||||
15348 | void Sema::CheckDelegatingCtorCycles() { | |||
15349 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; | |||
15350 | ||||
15351 | for (DelegatingCtorDeclsType::iterator | |||
15352 | I = DelegatingCtorDecls.begin(ExternalSource), | |||
15353 | E = DelegatingCtorDecls.end(); | |||
15354 | I != E; ++I) | |||
15355 | DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); | |||
15356 | ||||
15357 | for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) | |||
15358 | (*CI)->setInvalidDecl(); | |||
15359 | } | |||
15360 | ||||
15361 | namespace { | |||
15362 | /// AST visitor that finds references to the 'this' expression. | |||
15363 | class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { | |||
15364 | Sema &S; | |||
15365 | ||||
15366 | public: | |||
15367 | explicit FindCXXThisExpr(Sema &S) : S(S) { } | |||
15368 | ||||
15369 | bool VisitCXXThisExpr(CXXThisExpr *E) { | |||
15370 | S.Diag(E->getLocation(), diag::err_this_static_member_func) | |||
15371 | << E->isImplicit(); | |||
15372 | return false; | |||
15373 | } | |||
15374 | }; | |||
15375 | } | |||
15376 | ||||
15377 | bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { | |||
15378 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); | |||
15379 | if (!TSInfo) | |||
15380 | return false; | |||
15381 | ||||
15382 | TypeLoc TL = TSInfo->getTypeLoc(); | |||
15383 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); | |||
15384 | if (!ProtoTL) | |||
15385 | return false; | |||
15386 | ||||
15387 | // C++11 [expr.prim.general]p3: | |||
15388 | // [The expression this] shall not appear before the optional | |||
15389 | // cv-qualifier-seq and it shall not appear within the declaration of a | |||
15390 | // static member function (although its type and value category are defined | |||
15391 | // within a static member function as they are within a non-static member | |||
15392 | // function). [ Note: this is because declaration matching does not occur | |||
15393 | // until the complete declarator is known. - end note ] | |||
15394 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); | |||
15395 | FindCXXThisExpr Finder(*this); | |||
15396 | ||||
15397 | // If the return type came after the cv-qualifier-seq, check it now. | |||
15398 | if (Proto->hasTrailingReturn() && | |||
15399 | !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) | |||
15400 | return true; | |||
15401 | ||||
15402 | // Check the exception specification. | |||
15403 | if (checkThisInStaticMemberFunctionExceptionSpec(Method)) | |||
15404 | return true; | |||
15405 | ||||
15406 | return checkThisInStaticMemberFunctionAttributes(Method); | |||
15407 | } | |||
15408 | ||||
15409 | bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { | |||
15410 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); | |||
15411 | if (!TSInfo) | |||
15412 | return false; | |||
15413 | ||||
15414 | TypeLoc TL = TSInfo->getTypeLoc(); | |||
15415 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); | |||
15416 | if (!ProtoTL) | |||
15417 | return false; | |||
15418 | ||||
15419 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); | |||
15420 | FindCXXThisExpr Finder(*this); | |||
15421 | ||||
15422 | switch (Proto->getExceptionSpecType()) { | |||
15423 | case EST_Unparsed: | |||
15424 | case EST_Uninstantiated: | |||
15425 | case EST_Unevaluated: | |||
15426 | case EST_BasicNoexcept: | |||
15427 | case EST_DynamicNone: | |||
15428 | case EST_MSAny: | |||
15429 | case EST_None: | |||
15430 | break; | |||
15431 | ||||
15432 | case EST_DependentNoexcept: | |||
15433 | case EST_NoexceptFalse: | |||
15434 | case EST_NoexceptTrue: | |||
15435 | if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) | |||
15436 | return true; | |||
15437 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
15438 | ||||
15439 | case EST_Dynamic: | |||
15440 | for (const auto &E : Proto->exceptions()) { | |||
15441 | if (!Finder.TraverseType(E)) | |||
15442 | return true; | |||
15443 | } | |||
15444 | break; | |||
15445 | } | |||
15446 | ||||
15447 | return false; | |||
15448 | } | |||
15449 | ||||
15450 | bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { | |||
15451 | FindCXXThisExpr Finder(*this); | |||
15452 | ||||
15453 | // Check attributes. | |||
15454 | for (const auto *A : Method->attrs()) { | |||
15455 | // FIXME: This should be emitted by tblgen. | |||
15456 | Expr *Arg = nullptr; | |||
15457 | ArrayRef<Expr *> Args; | |||
15458 | if (const auto *G = dyn_cast<GuardedByAttr>(A)) | |||
15459 | Arg = G->getArg(); | |||
15460 | else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) | |||
15461 | Arg = G->getArg(); | |||
15462 | else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) | |||
15463 | Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); | |||
15464 | else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) | |||
15465 | Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); | |||
15466 | else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { | |||
15467 | Arg = ETLF->getSuccessValue(); | |||
15468 | Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); | |||
15469 | } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { | |||
15470 | Arg = STLF->getSuccessValue(); | |||
15471 | Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); | |||
15472 | } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) | |||
15473 | Arg = LR->getArg(); | |||
15474 | else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) | |||
15475 | Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); | |||
15476 | else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) | |||
15477 | Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); | |||
15478 | else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) | |||
15479 | Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); | |||
15480 | else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) | |||
15481 | Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); | |||
15482 | else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) | |||
15483 | Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); | |||
15484 | ||||
15485 | if (Arg && !Finder.TraverseStmt(Arg)) | |||
15486 | return true; | |||
15487 | ||||
15488 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
15489 | if (!Finder.TraverseStmt(Args[I])) | |||
15490 | return true; | |||
15491 | } | |||
15492 | } | |||
15493 | ||||
15494 | return false; | |||
15495 | } | |||
15496 | ||||
15497 | void Sema::checkExceptionSpecification( | |||
15498 | bool IsTopLevel, ExceptionSpecificationType EST, | |||
15499 | ArrayRef<ParsedType> DynamicExceptions, | |||
15500 | ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, | |||
15501 | SmallVectorImpl<QualType> &Exceptions, | |||
15502 | FunctionProtoType::ExceptionSpecInfo &ESI) { | |||
15503 | Exceptions.clear(); | |||
15504 | ESI.Type = EST; | |||
15505 | if (EST == EST_Dynamic) { | |||
15506 | Exceptions.reserve(DynamicExceptions.size()); | |||
15507 | for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { | |||
15508 | // FIXME: Preserve type source info. | |||
15509 | QualType ET = GetTypeFromParser(DynamicExceptions[ei]); | |||
15510 | ||||
15511 | if (IsTopLevel) { | |||
15512 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; | |||
15513 | collectUnexpandedParameterPacks(ET, Unexpanded); | |||
15514 | if (!Unexpanded.empty()) { | |||
15515 | DiagnoseUnexpandedParameterPacks( | |||
15516 | DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, | |||
15517 | Unexpanded); | |||
15518 | continue; | |||
15519 | } | |||
15520 | } | |||
15521 | ||||
15522 | // Check that the type is valid for an exception spec, and | |||
15523 | // drop it if not. | |||
15524 | if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) | |||
15525 | Exceptions.push_back(ET); | |||
15526 | } | |||
15527 | ESI.Exceptions = Exceptions; | |||
15528 | return; | |||
15529 | } | |||
15530 | ||||
15531 | if (isComputedNoexcept(EST)) { | |||
15532 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15535, __PRETTY_FUNCTION__)) | |||
15533 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15535, __PRETTY_FUNCTION__)) | |||
15534 | 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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15535, __PRETTY_FUNCTION__)) | |||
15535 | "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-9~svn360410/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 15535, __PRETTY_FUNCTION__)); | |||
15536 | if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { | |||
15537 | ESI.Type = EST_BasicNoexcept; | |||
15538 | return; | |||
15539 | } | |||
15540 | ||||
15541 | ESI.NoexceptExpr = NoexceptExpr; | |||
15542 | return; | |||
15543 | } | |||
15544 | } | |||
15545 | ||||
15546 | void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, | |||
15547 | ExceptionSpecificationType EST, | |||
15548 | SourceRange SpecificationRange, | |||
15549 | ArrayRef<ParsedType> DynamicExceptions, | |||
15550 | ArrayRef<SourceRange> DynamicExceptionRanges, | |||
15551 | Expr *NoexceptExpr) { | |||
15552 | if (!MethodD) | |||
15553 | return; | |||
15554 | ||||
15555 | // Dig out the method we're referring to. | |||
15556 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) | |||
15557 | MethodD = FunTmpl->getTemplatedDecl(); | |||
15558 | ||||
15559 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); | |||
15560 | if (!Method) | |||
15561 | return; | |||
15562 | ||||
15563 | // Check the exception specification. | |||
15564 | llvm::SmallVector<QualType, 4> Exceptions; | |||
15565 | FunctionProtoType::ExceptionSpecInfo ESI; | |||
15566 | checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, | |||
15567 | DynamicExceptionRanges, NoexceptExpr, Exceptions, | |||
15568 | ESI); | |||
15569 | ||||
15570 | // Update the exception specification on the function type. | |||
15571 | Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); | |||
15572 | ||||
15573 | if (Method->isStatic()) | |||
15574 | checkThisInStaticMemberFunctionExceptionSpec(Method); | |||
15575 | ||||
15576 | if (Method->isVirtual()) { | |||
15577 | // Check overrides, which we previously had to delay. | |||
15578 | for (const CXXMethodDecl *O : Method->overridden_methods()) | |||
15579 | CheckOverridingFunctionExceptionSpec(Method, O); | |||
15580 | } | |||
15581 | } | |||
15582 | ||||
15583 | /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. | |||
15584 | /// | |||
15585 | MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, | |||
15586 | SourceLocation DeclStart, Declarator &D, | |||
15587 | Expr *BitWidth, | |||
15588 | InClassInitStyle InitStyle, | |||
15589 | AccessSpecifier AS, | |||
15590 | const ParsedAttr &MSPropertyAttr) { | |||
15591 | IdentifierInfo *II = D.getIdentifier(); | |||
15592 | if (!II) { | |||
15593 | Diag(DeclStart, diag::err_anonymous_property); | |||
15594 | return nullptr; | |||
15595 | } | |||
15596 | SourceLocation Loc = D.getIdentifierLoc(); | |||
15597 | ||||
15598 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
15599 | QualType T = TInfo->getType(); | |||
15600 | if (getLangOpts().CPlusPlus) { | |||
15601 | CheckExtraCXXDefaultArguments(D); | |||
15602 | ||||
15603 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
15604 | UPPC_DataMemberType)) { | |||
15605 | D.setInvalidType(); | |||
15606 | T = Context.IntTy; | |||
15607 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
15608 | } | |||
15609 | } | |||
15610 | ||||
15611 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
15612 | ||||
15613 | if (D.getDeclSpec().isInlineSpecified()) | |||
15614 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
15615 | << getLangOpts().CPlusPlus17; | |||
15616 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
15617 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
15618 | diag::err_invalid_thread) | |||
15619 | << DeclSpec::getSpecifierName(TSCS); | |||
15620 | ||||
15621 | // Check to see if this name was declared as a member previously | |||
15622 | NamedDecl *PrevDecl = nullptr; | |||
15623 | LookupResult Previous(*this, II, Loc, LookupMemberName, | |||
15624 | ForVisibleRedeclaration); | |||
15625 | LookupName(Previous, S); | |||
15626 | switch (Previous.getResultKind()) { | |||
15627 | case LookupResult::Found: | |||
15628 | case LookupResult::FoundUnresolvedValue: | |||
15629 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | |||
15630 | break; | |||
15631 | ||||
15632 | case LookupResult::FoundOverloaded: | |||
15633 | PrevDecl = Previous.getRepresentativeDecl(); | |||
15634 | break; | |||
15635 | ||||
15636 | case LookupResult::NotFound: | |||
15637 | case LookupResult::NotFoundInCurrentInstantiation: | |||
15638 | case LookupResult::Ambiguous: | |||
15639 | break; | |||
15640 | } | |||
15641 | ||||
15642 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | |||
15643 | // Maybe we will complain about the shadowed template parameter. | |||
15644 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
15645 | // Just pretend that we didn't see the previous declaration. | |||
15646 | PrevDecl = nullptr; | |||
15647 | } | |||
15648 | ||||
15649 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | |||
15650 | PrevDecl = nullptr; | |||
15651 | ||||
15652 | SourceLocation TSSL = D.getBeginLoc(); | |||
15653 | MSPropertyDecl *NewPD = | |||
15654 | MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, | |||
15655 | MSPropertyAttr.getPropertyDataGetter(), | |||
15656 | MSPropertyAttr.getPropertyDataSetter()); | |||
15657 | ProcessDeclAttributes(TUScope, NewPD, D); | |||
15658 | NewPD->setAccess(AS); | |||
15659 | ||||
15660 | if (NewPD->isInvalidDecl()) | |||
15661 | Record->setInvalidDecl(); | |||
15662 | ||||
15663 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
15664 | NewPD->setModulePrivate(); | |||
15665 | ||||
15666 | if (NewPD->isInvalidDecl() && PrevDecl) { | |||
15667 | // Don't introduce NewFD into scope; there's already something | |||
15668 | // with the same name in the same scope. | |||
15669 | } else if (II) { | |||
15670 | PushOnScopeChains(NewPD, S); | |||
15671 | } else | |||
15672 | Record->addDecl(NewPD); | |||
15673 | ||||
15674 | return NewPD; | |||
15675 | } |
1 | //===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 Sema class, which performs semantic analysis and | |||
10 | // builds ASTs. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #ifndef LLVM_CLANG_SEMA_SEMA_H | |||
15 | #define LLVM_CLANG_SEMA_SEMA_H | |||
16 | ||||
17 | #include "clang/AST/Attr.h" | |||
18 | #include "clang/AST/Availability.h" | |||
19 | #include "clang/AST/ComparisonCategories.h" | |||
20 | #include "clang/AST/DeclTemplate.h" | |||
21 | #include "clang/AST/DeclarationName.h" | |||
22 | #include "clang/AST/Expr.h" | |||
23 | #include "clang/AST/ExprCXX.h" | |||
24 | #include "clang/AST/ExprObjC.h" | |||
25 | #include "clang/AST/ExternalASTSource.h" | |||
26 | #include "clang/AST/LocInfoType.h" | |||
27 | #include "clang/AST/MangleNumberingContext.h" | |||
28 | #include "clang/AST/NSAPI.h" | |||
29 | #include "clang/AST/PrettyPrinter.h" | |||
30 | #include "clang/AST/StmtCXX.h" | |||
31 | #include "clang/AST/TypeLoc.h" | |||
32 | #include "clang/AST/TypeOrdering.h" | |||
33 | #include "clang/Basic/ExpressionTraits.h" | |||
34 | #include "clang/Basic/Module.h" | |||
35 | #include "clang/Basic/OpenMPKinds.h" | |||
36 | #include "clang/Basic/PragmaKinds.h" | |||
37 | #include "clang/Basic/Specifiers.h" | |||
38 | #include "clang/Basic/TemplateKinds.h" | |||
39 | #include "clang/Basic/TypeTraits.h" | |||
40 | #include "clang/Sema/AnalysisBasedWarnings.h" | |||
41 | #include "clang/Sema/CleanupInfo.h" | |||
42 | #include "clang/Sema/DeclSpec.h" | |||
43 | #include "clang/Sema/ExternalSemaSource.h" | |||
44 | #include "clang/Sema/IdentifierResolver.h" | |||
45 | #include "clang/Sema/ObjCMethodList.h" | |||
46 | #include "clang/Sema/Ownership.h" | |||
47 | #include "clang/Sema/Scope.h" | |||
48 | #include "clang/Sema/TypoCorrection.h" | |||
49 | #include "clang/Sema/Weak.h" | |||
50 | #include "llvm/ADT/ArrayRef.h" | |||
51 | #include "llvm/ADT/Optional.h" | |||
52 | #include "llvm/ADT/SetVector.h" | |||
53 | #include "llvm/ADT/SmallBitVector.h" | |||
54 | #include "llvm/ADT/SmallPtrSet.h" | |||
55 | #include "llvm/ADT/SmallVector.h" | |||
56 | #include "llvm/ADT/TinyPtrVector.h" | |||
57 | #include <deque> | |||
58 | #include <memory> | |||
59 | #include <string> | |||
60 | #include <vector> | |||
61 | ||||
62 | namespace llvm { | |||
63 | class APSInt; | |||
64 | template <typename ValueT> struct DenseMapInfo; | |||
65 | template <typename ValueT, typename ValueInfoT> class DenseSet; | |||
66 | class SmallBitVector; | |||
67 | struct InlineAsmIdentifierInfo; | |||
68 | } | |||
69 | ||||
70 | namespace clang { | |||
71 | class ADLResult; | |||
72 | class ASTConsumer; | |||
73 | class ASTContext; | |||
74 | class ASTMutationListener; | |||
75 | class ASTReader; | |||
76 | class ASTWriter; | |||
77 | class ArrayType; | |||
78 | class ParsedAttr; | |||
79 | class BindingDecl; | |||
80 | class BlockDecl; | |||
81 | class CapturedDecl; | |||
82 | class CXXBasePath; | |||
83 | class CXXBasePaths; | |||
84 | class CXXBindTemporaryExpr; | |||
85 | typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; | |||
86 | class CXXConstructorDecl; | |||
87 | class CXXConversionDecl; | |||
88 | class CXXDeleteExpr; | |||
89 | class CXXDestructorDecl; | |||
90 | class CXXFieldCollector; | |||
91 | class CXXMemberCallExpr; | |||
92 | class CXXMethodDecl; | |||
93 | class CXXScopeSpec; | |||
94 | class CXXTemporary; | |||
95 | class CXXTryStmt; | |||
96 | class CallExpr; | |||
97 | class ClassTemplateDecl; | |||
98 | class ClassTemplatePartialSpecializationDecl; | |||
99 | class ClassTemplateSpecializationDecl; | |||
100 | class VarTemplatePartialSpecializationDecl; | |||
101 | class CodeCompleteConsumer; | |||
102 | class CodeCompletionAllocator; | |||
103 | class CodeCompletionTUInfo; | |||
104 | class CodeCompletionResult; | |||
105 | class CoroutineBodyStmt; | |||
106 | class Decl; | |||
107 | class DeclAccessPair; | |||
108 | class DeclContext; | |||
109 | class DeclRefExpr; | |||
110 | class DeclaratorDecl; | |||
111 | class DeducedTemplateArgument; | |||
112 | class DependentDiagnostic; | |||
113 | class DesignatedInitExpr; | |||
114 | class Designation; | |||
115 | class EnableIfAttr; | |||
116 | class EnumConstantDecl; | |||
117 | class Expr; | |||
118 | class ExtVectorType; | |||
119 | class FormatAttr; | |||
120 | class FriendDecl; | |||
121 | class FunctionDecl; | |||
122 | class FunctionProtoType; | |||
123 | class FunctionTemplateDecl; | |||
124 | class ImplicitConversionSequence; | |||
125 | typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; | |||
126 | class InitListExpr; | |||
127 | class InitializationKind; | |||
128 | class InitializationSequence; | |||
129 | class InitializedEntity; | |||
130 | class IntegerLiteral; | |||
131 | class LabelStmt; | |||
132 | class LambdaExpr; | |||
133 | class LangOptions; | |||
134 | class LocalInstantiationScope; | |||
135 | class LookupResult; | |||
136 | class MacroInfo; | |||
137 | typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; | |||
138 | class ModuleLoader; | |||
139 | class MultiLevelTemplateArgumentList; | |||
140 | class NamedDecl; | |||
141 | class ObjCCategoryDecl; | |||
142 | class ObjCCategoryImplDecl; | |||
143 | class ObjCCompatibleAliasDecl; | |||
144 | class ObjCContainerDecl; | |||
145 | class ObjCImplDecl; | |||
146 | class ObjCImplementationDecl; | |||
147 | class ObjCInterfaceDecl; | |||
148 | class ObjCIvarDecl; | |||
149 | template <class T> class ObjCList; | |||
150 | class ObjCMessageExpr; | |||
151 | class ObjCMethodDecl; | |||
152 | class ObjCPropertyDecl; | |||
153 | class ObjCProtocolDecl; | |||
154 | class OMPThreadPrivateDecl; | |||
155 | class OMPRequiresDecl; | |||
156 | class OMPDeclareReductionDecl; | |||
157 | class OMPDeclareSimdDecl; | |||
158 | class OMPClause; | |||
159 | struct OMPVarListLocTy; | |||
160 | struct OverloadCandidate; | |||
161 | class OverloadCandidateSet; | |||
162 | class OverloadExpr; | |||
163 | class ParenListExpr; | |||
164 | class ParmVarDecl; | |||
165 | class Preprocessor; | |||
166 | class PseudoDestructorTypeStorage; | |||
167 | class PseudoObjectExpr; | |||
168 | class QualType; | |||
169 | class StandardConversionSequence; | |||
170 | class Stmt; | |||
171 | class StringLiteral; | |||
172 | class SwitchStmt; | |||
173 | class TemplateArgument; | |||
174 | class TemplateArgumentList; | |||
175 | class TemplateArgumentLoc; | |||
176 | class TemplateDecl; | |||
177 | class TemplateInstantiationCallback; | |||
178 | class TemplateParameterList; | |||
179 | class TemplatePartialOrderingContext; | |||
180 | class TemplateTemplateParmDecl; | |||
181 | class Token; | |||
182 | class TypeAliasDecl; | |||
183 | class TypedefDecl; | |||
184 | class TypedefNameDecl; | |||
185 | class TypeLoc; | |||
186 | class TypoCorrectionConsumer; | |||
187 | class UnqualifiedId; | |||
188 | class UnresolvedLookupExpr; | |||
189 | class UnresolvedMemberExpr; | |||
190 | class UnresolvedSetImpl; | |||
191 | class UnresolvedSetIterator; | |||
192 | class UsingDecl; | |||
193 | class UsingShadowDecl; | |||
194 | class ValueDecl; | |||
195 | class VarDecl; | |||
196 | class VarTemplateSpecializationDecl; | |||
197 | class VisibilityAttr; | |||
198 | class VisibleDeclConsumer; | |||
199 | class IndirectFieldDecl; | |||
200 | struct DeductionFailureInfo; | |||
201 | class TemplateSpecCandidateSet; | |||
202 | ||||
203 | namespace sema { | |||
204 | class AccessedEntity; | |||
205 | class BlockScopeInfo; | |||
206 | class Capture; | |||
207 | class CapturedRegionScopeInfo; | |||
208 | class CapturingScopeInfo; | |||
209 | class CompoundScopeInfo; | |||
210 | class DelayedDiagnostic; | |||
211 | class DelayedDiagnosticPool; | |||
212 | class FunctionScopeInfo; | |||
213 | class LambdaScopeInfo; | |||
214 | class PossiblyUnreachableDiag; | |||
215 | class SemaPPCallbacks; | |||
216 | class TemplateDeductionInfo; | |||
217 | } | |||
218 | ||||
219 | namespace threadSafety { | |||
220 | class BeforeSet; | |||
221 | void threadSafetyCleanup(BeforeSet* Cache); | |||
222 | } | |||
223 | ||||
224 | // FIXME: No way to easily map from TemplateTypeParmTypes to | |||
225 | // TemplateTypeParmDecls, so we have this horrible PointerUnion. | |||
226 | typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, | |||
227 | SourceLocation> UnexpandedParameterPack; | |||
228 | ||||
229 | /// Describes whether we've seen any nullability information for the given | |||
230 | /// file. | |||
231 | struct FileNullability { | |||
232 | /// The first pointer declarator (of any pointer kind) in the file that does | |||
233 | /// not have a corresponding nullability annotation. | |||
234 | SourceLocation PointerLoc; | |||
235 | ||||
236 | /// The end location for the first pointer declarator in the file. Used for | |||
237 | /// placing fix-its. | |||
238 | SourceLocation PointerEndLoc; | |||
239 | ||||
240 | /// Which kind of pointer declarator we saw. | |||
241 | uint8_t PointerKind; | |||
242 | ||||
243 | /// Whether we saw any type nullability annotations in the given file. | |||
244 | bool SawTypeNullability = false; | |||
245 | }; | |||
246 | ||||
247 | /// A mapping from file IDs to a record of whether we've seen nullability | |||
248 | /// information in that file. | |||
249 | class FileNullabilityMap { | |||
250 | /// A mapping from file IDs to the nullability information for each file ID. | |||
251 | llvm::DenseMap<FileID, FileNullability> Map; | |||
252 | ||||
253 | /// A single-element cache based on the file ID. | |||
254 | struct { | |||
255 | FileID File; | |||
256 | FileNullability Nullability; | |||
257 | } Cache; | |||
258 | ||||
259 | public: | |||
260 | FileNullability &operator[](FileID file) { | |||
261 | // Check the single-element cache. | |||
262 | if (file == Cache.File) | |||
263 | return Cache.Nullability; | |||
264 | ||||
265 | // It's not in the single-element cache; flush the cache if we have one. | |||
266 | if (!Cache.File.isInvalid()) { | |||
267 | Map[Cache.File] = Cache.Nullability; | |||
268 | } | |||
269 | ||||
270 | // Pull this entry into the cache. | |||
271 | Cache.File = file; | |||
272 | Cache.Nullability = Map[file]; | |||
273 | return Cache.Nullability; | |||
274 | } | |||
275 | }; | |||
276 | ||||
277 | /// Keeps track of expected type during expression parsing. The type is tied to | |||
278 | /// a particular token, all functions that update or consume the type take a | |||
279 | /// start location of the token they are looking at as a parameter. This allows | |||
280 | /// to avoid updating the type on hot paths in the parser. | |||
281 | class PreferredTypeBuilder { | |||
282 | public: | |||
283 | PreferredTypeBuilder() = default; | |||
284 | explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} | |||
285 | ||||
286 | void enterCondition(Sema &S, SourceLocation Tok); | |||
287 | void enterReturn(Sema &S, SourceLocation Tok); | |||
288 | void enterVariableInit(SourceLocation Tok, Decl *D); | |||
289 | /// Computing a type for the function argument may require running | |||
290 | /// overloading, so we postpone its computation until it is actually needed. | |||
291 | /// | |||
292 | /// Clients should be very careful when using this funciton, as it stores a | |||
293 | /// function_ref, clients should make sure all calls to get() with the same | |||
294 | /// location happen while function_ref is alive. | |||
295 | void enterFunctionArgument(SourceLocation Tok, | |||
296 | llvm::function_ref<QualType()> ComputeType); | |||
297 | ||||
298 | void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); | |||
299 | void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, | |||
300 | SourceLocation OpLoc); | |||
301 | void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); | |||
302 | void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); | |||
303 | void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); | |||
304 | /// Handles all type casts, including C-style cast, C++ casts, etc. | |||
305 | void enterTypeCast(SourceLocation Tok, QualType CastType); | |||
306 | ||||
307 | QualType get(SourceLocation Tok) const { | |||
308 | if (Tok != ExpectedLoc) | |||
309 | return QualType(); | |||
310 | if (!Type.isNull()) | |||
311 | return Type; | |||
312 | if (ComputeType) | |||
313 | return ComputeType(); | |||
314 | return QualType(); | |||
315 | } | |||
316 | ||||
317 | private: | |||
318 | /// Start position of a token for which we store expected type. | |||
319 | SourceLocation ExpectedLoc; | |||
320 | /// Expected type for a token starting at ExpectedLoc. | |||
321 | QualType Type; | |||
322 | /// A function to compute expected type at ExpectedLoc. It is only considered | |||
323 | /// if Type is null. | |||
324 | llvm::function_ref<QualType()> ComputeType; | |||
325 | }; | |||
326 | ||||
327 | /// Sema - This implements semantic analysis and AST building for C. | |||
328 | class Sema { | |||
329 | Sema(const Sema &) = delete; | |||
330 | void operator=(const Sema &) = delete; | |||
331 | ||||
332 | ///Source of additional semantic information. | |||
333 | ExternalSemaSource *ExternalSource; | |||
334 | ||||
335 | ///Whether Sema has generated a multiplexer and has to delete it. | |||
336 | bool isMultiplexExternalSource; | |||
337 | ||||
338 | static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); | |||
339 | ||||
340 | bool isVisibleSlow(const NamedDecl *D); | |||
341 | ||||
342 | /// Determine whether two declarations should be linked together, given that | |||
343 | /// the old declaration might not be visible and the new declaration might | |||
344 | /// not have external linkage. | |||
345 | bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, | |||
346 | const NamedDecl *New) { | |||
347 | if (isVisible(Old)) | |||
348 | return true; | |||
349 | // See comment in below overload for why it's safe to compute the linkage | |||
350 | // of the new declaration here. | |||
351 | if (New->isExternallyDeclarable()) { | |||
352 | assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl" ) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 353, __PRETTY_FUNCTION__)) | |||
353 | "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl" ) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 353, __PRETTY_FUNCTION__)); | |||
354 | return true; | |||
355 | } | |||
356 | return false; | |||
357 | } | |||
358 | bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); | |||
359 | ||||
360 | void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, | |||
361 | QualType ResultTy, | |||
362 | ArrayRef<QualType> Args); | |||
363 | ||||
364 | public: | |||
365 | typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; | |||
366 | typedef OpaquePtr<TemplateName> TemplateTy; | |||
367 | typedef OpaquePtr<QualType> TypeTy; | |||
368 | ||||
369 | OpenCLOptions OpenCLFeatures; | |||
370 | FPOptions FPFeatures; | |||
371 | ||||
372 | const LangOptions &LangOpts; | |||
373 | Preprocessor &PP; | |||
374 | ASTContext &Context; | |||
375 | ASTConsumer &Consumer; | |||
376 | DiagnosticsEngine &Diags; | |||
377 | SourceManager &SourceMgr; | |||
378 | ||||
379 | /// Flag indicating whether or not to collect detailed statistics. | |||
380 | bool CollectStats; | |||
381 | ||||
382 | /// Code-completion consumer. | |||
383 | CodeCompleteConsumer *CodeCompleter; | |||
384 | ||||
385 | /// CurContext - This is the current declaration context of parsing. | |||
386 | DeclContext *CurContext; | |||
387 | ||||
388 | /// Generally null except when we temporarily switch decl contexts, | |||
389 | /// like in \see ActOnObjCTemporaryExitContainerContext. | |||
390 | DeclContext *OriginalLexicalContext; | |||
391 | ||||
392 | /// VAListTagName - The declaration name corresponding to __va_list_tag. | |||
393 | /// This is used as part of a hack to omit that class from ADL results. | |||
394 | DeclarationName VAListTagName; | |||
395 | ||||
396 | bool MSStructPragmaOn; // True when \#pragma ms_struct on | |||
397 | ||||
398 | /// Controls member pointer representation format under the MS ABI. | |||
399 | LangOptions::PragmaMSPointersToMembersKind | |||
400 | MSPointerToMemberRepresentationMethod; | |||
401 | ||||
402 | /// Stack of active SEH __finally scopes. Can be empty. | |||
403 | SmallVector<Scope*, 2> CurrentSEHFinally; | |||
404 | ||||
405 | /// Source location for newly created implicit MSInheritanceAttrs | |||
406 | SourceLocation ImplicitMSInheritanceAttrLoc; | |||
407 | ||||
408 | /// pragma clang section kind | |||
409 | enum PragmaClangSectionKind { | |||
410 | PCSK_Invalid = 0, | |||
411 | PCSK_BSS = 1, | |||
412 | PCSK_Data = 2, | |||
413 | PCSK_Rodata = 3, | |||
414 | PCSK_Text = 4 | |||
415 | }; | |||
416 | ||||
417 | enum PragmaClangSectionAction { | |||
418 | PCSA_Set = 0, | |||
419 | PCSA_Clear = 1 | |||
420 | }; | |||
421 | ||||
422 | struct PragmaClangSection { | |||
423 | std::string SectionName; | |||
424 | bool Valid = false; | |||
425 | SourceLocation PragmaLocation; | |||
426 | ||||
427 | void Act(SourceLocation PragmaLocation, | |||
428 | PragmaClangSectionAction Action, | |||
429 | StringLiteral* Name); | |||
430 | }; | |||
431 | ||||
432 | PragmaClangSection PragmaClangBSSSection; | |||
433 | PragmaClangSection PragmaClangDataSection; | |||
434 | PragmaClangSection PragmaClangRodataSection; | |||
435 | PragmaClangSection PragmaClangTextSection; | |||
436 | ||||
437 | enum PragmaMsStackAction { | |||
438 | PSK_Reset = 0x0, // #pragma () | |||
439 | PSK_Set = 0x1, // #pragma (value) | |||
440 | PSK_Push = 0x2, // #pragma (push[, id]) | |||
441 | PSK_Pop = 0x4, // #pragma (pop[, id]) | |||
442 | PSK_Show = 0x8, // #pragma (show) -- only for "pack"! | |||
443 | PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) | |||
444 | PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) | |||
445 | }; | |||
446 | ||||
447 | template<typename ValueType> | |||
448 | struct PragmaStack { | |||
449 | struct Slot { | |||
450 | llvm::StringRef StackSlotLabel; | |||
451 | ValueType Value; | |||
452 | SourceLocation PragmaLocation; | |||
453 | SourceLocation PragmaPushLocation; | |||
454 | Slot(llvm::StringRef StackSlotLabel, ValueType Value, | |||
455 | SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) | |||
456 | : StackSlotLabel(StackSlotLabel), Value(Value), | |||
457 | PragmaLocation(PragmaLocation), | |||
458 | PragmaPushLocation(PragmaPushLocation) {} | |||
459 | }; | |||
460 | void Act(SourceLocation PragmaLocation, | |||
461 | PragmaMsStackAction Action, | |||
462 | llvm::StringRef StackSlotLabel, | |||
463 | ValueType Value); | |||
464 | ||||
465 | // MSVC seems to add artificial slots to #pragma stacks on entering a C++ | |||
466 | // method body to restore the stacks on exit, so it works like this: | |||
467 | // | |||
468 | // struct S { | |||
469 | // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) | |||
470 | // void Method {} | |||
471 | // #pragma <name>(pop, InternalPragmaSlot) | |||
472 | // }; | |||
473 | // | |||
474 | // It works even with #pragma vtordisp, although MSVC doesn't support | |||
475 | // #pragma vtordisp(push [, id], n) | |||
476 | // syntax. | |||
477 | // | |||
478 | // Push / pop a named sentinel slot. | |||
479 | void SentinelAction(PragmaMsStackAction Action, StringRef Label) { | |||
480 | assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!" ) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 481, __PRETTY_FUNCTION__)) | |||
481 | "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!" ) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 481, __PRETTY_FUNCTION__)); | |||
482 | Act(CurrentPragmaLocation, Action, Label, CurrentValue); | |||
483 | } | |||
484 | ||||
485 | // Constructors. | |||
486 | explicit PragmaStack(const ValueType &Default) | |||
487 | : DefaultValue(Default), CurrentValue(Default) {} | |||
488 | ||||
489 | bool hasValue() const { return CurrentValue != DefaultValue; } | |||
490 | ||||
491 | SmallVector<Slot, 2> Stack; | |||
492 | ValueType DefaultValue; // Value used for PSK_Reset action. | |||
493 | ValueType CurrentValue; | |||
494 | SourceLocation CurrentPragmaLocation; | |||
495 | }; | |||
496 | // FIXME: We should serialize / deserialize these if they occur in a PCH (but | |||
497 | // we shouldn't do so if they're in a module). | |||
498 | ||||
499 | /// Whether to insert vtordisps prior to virtual bases in the Microsoft | |||
500 | /// C++ ABI. Possible values are 0, 1, and 2, which mean: | |||
501 | /// | |||
502 | /// 0: Suppress all vtordisps | |||
503 | /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial | |||
504 | /// structors | |||
505 | /// 2: Always insert vtordisps to support RTTI on partially constructed | |||
506 | /// objects | |||
507 | PragmaStack<MSVtorDispAttr::Mode> VtorDispStack; | |||
508 | // #pragma pack. | |||
509 | // Sentinel to represent when the stack is set to mac68k alignment. | |||
510 | static const unsigned kMac68kAlignmentSentinel = ~0U; | |||
511 | PragmaStack<unsigned> PackStack; | |||
512 | // The current #pragma pack values and locations at each #include. | |||
513 | struct PackIncludeState { | |||
514 | unsigned CurrentValue; | |||
515 | SourceLocation CurrentPragmaLocation; | |||
516 | bool HasNonDefaultValue, ShouldWarnOnInclude; | |||
517 | }; | |||
518 | SmallVector<PackIncludeState, 8> PackIncludeStack; | |||
519 | // Segment #pragmas. | |||
520 | PragmaStack<StringLiteral *> DataSegStack; | |||
521 | PragmaStack<StringLiteral *> BSSSegStack; | |||
522 | PragmaStack<StringLiteral *> ConstSegStack; | |||
523 | PragmaStack<StringLiteral *> CodeSegStack; | |||
524 | ||||
525 | // RAII object to push / pop sentinel slots for all MS #pragma stacks. | |||
526 | // Actions should be performed only if we enter / exit a C++ method body. | |||
527 | class PragmaStackSentinelRAII { | |||
528 | public: | |||
529 | PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); | |||
530 | ~PragmaStackSentinelRAII(); | |||
531 | ||||
532 | private: | |||
533 | Sema &S; | |||
534 | StringRef SlotLabel; | |||
535 | bool ShouldAct; | |||
536 | }; | |||
537 | ||||
538 | /// A mapping that describes the nullability we've seen in each header file. | |||
539 | FileNullabilityMap NullabilityMap; | |||
540 | ||||
541 | /// Last section used with #pragma init_seg. | |||
542 | StringLiteral *CurInitSeg; | |||
543 | SourceLocation CurInitSegLoc; | |||
544 | ||||
545 | /// VisContext - Manages the stack for \#pragma GCC visibility. | |||
546 | void *VisContext; // Really a "PragmaVisStack*" | |||
547 | ||||
548 | /// This an attribute introduced by \#pragma clang attribute. | |||
549 | struct PragmaAttributeEntry { | |||
550 | SourceLocation Loc; | |||
551 | ParsedAttr *Attribute; | |||
552 | SmallVector<attr::SubjectMatchRule, 4> MatchRules; | |||
553 | bool IsUsed; | |||
554 | }; | |||
555 | ||||
556 | /// A push'd group of PragmaAttributeEntries. | |||
557 | struct PragmaAttributeGroup { | |||
558 | /// The location of the push attribute. | |||
559 | SourceLocation Loc; | |||
560 | /// The namespace of this push group. | |||
561 | const IdentifierInfo *Namespace; | |||
562 | SmallVector<PragmaAttributeEntry, 2> Entries; | |||
563 | }; | |||
564 | ||||
565 | SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; | |||
566 | ||||
567 | /// The declaration that is currently receiving an attribute from the | |||
568 | /// #pragma attribute stack. | |||
569 | const Decl *PragmaAttributeCurrentTargetDecl; | |||
570 | ||||
571 | /// This represents the last location of a "#pragma clang optimize off" | |||
572 | /// directive if such a directive has not been closed by an "on" yet. If | |||
573 | /// optimizations are currently "on", this is set to an invalid location. | |||
574 | SourceLocation OptimizeOffPragmaLocation; | |||
575 | ||||
576 | /// Flag indicating if Sema is building a recovery call expression. | |||
577 | /// | |||
578 | /// This flag is used to avoid building recovery call expressions | |||
579 | /// if Sema is already doing so, which would cause infinite recursions. | |||
580 | bool IsBuildingRecoveryCallExpr; | |||
581 | ||||
582 | /// Used to control the generation of ExprWithCleanups. | |||
583 | CleanupInfo Cleanup; | |||
584 | ||||
585 | /// ExprCleanupObjects - This is the stack of objects requiring | |||
586 | /// cleanup that are created by the current full expression. The | |||
587 | /// element type here is ExprWithCleanups::Object. | |||
588 | SmallVector<BlockDecl*, 8> ExprCleanupObjects; | |||
589 | ||||
590 | /// Store a set of either DeclRefExprs or MemberExprs that contain a reference | |||
591 | /// to a variable (constant) that may or may not be odr-used in this Expr, and | |||
592 | /// we won't know until all lvalue-to-rvalue and discarded value conversions | |||
593 | /// have been applied to all subexpressions of the enclosing full expression. | |||
594 | /// This is cleared at the end of each full expression. | |||
595 | using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>; | |||
596 | MaybeODRUseExprSet MaybeODRUseExprs; | |||
597 | ||||
598 | std::unique_ptr<sema::FunctionScopeInfo> PreallocatedFunctionScope; | |||
599 | ||||
600 | /// Stack containing information about each of the nested | |||
601 | /// function, block, and method scopes that are currently active. | |||
602 | SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; | |||
603 | ||||
604 | typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, | |||
605 | &ExternalSemaSource::ReadExtVectorDecls, 2, 2> | |||
606 | ExtVectorDeclsType; | |||
607 | ||||
608 | /// ExtVectorDecls - This is a list all the extended vector types. This allows | |||
609 | /// us to associate a raw vector type with one of the ext_vector type names. | |||
610 | /// This is only necessary for issuing pretty diagnostics. | |||
611 | ExtVectorDeclsType ExtVectorDecls; | |||
612 | ||||
613 | /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. | |||
614 | std::unique_ptr<CXXFieldCollector> FieldCollector; | |||
615 | ||||
616 | typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; | |||
617 | ||||
618 | /// Set containing all declared private fields that are not used. | |||
619 | NamedDeclSetType UnusedPrivateFields; | |||
620 | ||||
621 | /// Set containing all typedefs that are likely unused. | |||
622 | llvm::SmallSetVector<const TypedefNameDecl *, 4> | |||
623 | UnusedLocalTypedefNameCandidates; | |||
624 | ||||
625 | /// Delete-expressions to be analyzed at the end of translation unit | |||
626 | /// | |||
627 | /// This list contains class members, and locations of delete-expressions | |||
628 | /// that could not be proven as to whether they mismatch with new-expression | |||
629 | /// used in initializer of the field. | |||
630 | typedef std::pair<SourceLocation, bool> DeleteExprLoc; | |||
631 | typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; | |||
632 | llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; | |||
633 | ||||
634 | typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; | |||
635 | ||||
636 | /// PureVirtualClassDiagSet - a set of class declarations which we have | |||
637 | /// emitted a list of pure virtual functions. Used to prevent emitting the | |||
638 | /// same list more than once. | |||
639 | std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; | |||
640 | ||||
641 | /// ParsingInitForAutoVars - a set of declarations with auto types for which | |||
642 | /// we are currently parsing the initializer. | |||
643 | llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; | |||
644 | ||||
645 | /// Look for a locally scoped extern "C" declaration by the given name. | |||
646 | NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); | |||
647 | ||||
648 | typedef LazyVector<VarDecl *, ExternalSemaSource, | |||
649 | &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> | |||
650 | TentativeDefinitionsType; | |||
651 | ||||
652 | /// All the tentative definitions encountered in the TU. | |||
653 | TentativeDefinitionsType TentativeDefinitions; | |||
654 | ||||
655 | typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, | |||
656 | &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> | |||
657 | UnusedFileScopedDeclsType; | |||
658 | ||||
659 | /// The set of file scoped decls seen so far that have not been used | |||
660 | /// and must warn if not used. Only contains the first declaration. | |||
661 | UnusedFileScopedDeclsType UnusedFileScopedDecls; | |||
662 | ||||
663 | typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, | |||
664 | &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> | |||
665 | DelegatingCtorDeclsType; | |||
666 | ||||
667 | /// All the delegating constructors seen so far in the file, used for | |||
668 | /// cycle detection at the end of the TU. | |||
669 | DelegatingCtorDeclsType DelegatingCtorDecls; | |||
670 | ||||
671 | /// All the overriding functions seen during a class definition | |||
672 | /// that had their exception spec checks delayed, plus the overridden | |||
673 | /// function. | |||
674 | SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> | |||
675 | DelayedOverridingExceptionSpecChecks; | |||
676 | ||||
677 | /// All the function redeclarations seen during a class definition that had | |||
678 | /// their exception spec checks delayed, plus the prior declaration they | |||
679 | /// should be checked against. Except during error recovery, the new decl | |||
680 | /// should always be a friend declaration, as that's the only valid way to | |||
681 | /// redeclare a special member before its class is complete. | |||
682 | SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> | |||
683 | DelayedEquivalentExceptionSpecChecks; | |||
684 | ||||
685 | typedef llvm::MapVector<const FunctionDecl *, | |||
686 | std::unique_ptr<LateParsedTemplate>> | |||
687 | LateParsedTemplateMapT; | |||
688 | LateParsedTemplateMapT LateParsedTemplateMap; | |||
689 | ||||
690 | /// Callback to the parser to parse templated functions when needed. | |||
691 | typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); | |||
692 | typedef void LateTemplateParserCleanupCB(void *P); | |||
693 | LateTemplateParserCB *LateTemplateParser; | |||
694 | LateTemplateParserCleanupCB *LateTemplateParserCleanup; | |||
695 | void *OpaqueParser; | |||
696 | ||||
697 | void SetLateTemplateParser(LateTemplateParserCB *LTP, | |||
698 | LateTemplateParserCleanupCB *LTPCleanup, | |||
699 | void *P) { | |||
700 | LateTemplateParser = LTP; | |||
701 | LateTemplateParserCleanup = LTPCleanup; | |||
702 | OpaqueParser = P; | |||
703 | } | |||
704 | ||||
705 | class DelayedDiagnostics; | |||
706 | ||||
707 | class DelayedDiagnosticsState { | |||
708 | sema::DelayedDiagnosticPool *SavedPool; | |||
709 | friend class Sema::DelayedDiagnostics; | |||
710 | }; | |||
711 | typedef DelayedDiagnosticsState ParsingDeclState; | |||
712 | typedef DelayedDiagnosticsState ProcessingContextState; | |||
713 | ||||
714 | /// A class which encapsulates the logic for delaying diagnostics | |||
715 | /// during parsing and other processing. | |||
716 | class DelayedDiagnostics { | |||
717 | /// The current pool of diagnostics into which delayed | |||
718 | /// diagnostics should go. | |||
719 | sema::DelayedDiagnosticPool *CurPool; | |||
720 | ||||
721 | public: | |||
722 | DelayedDiagnostics() : CurPool(nullptr) {} | |||
723 | ||||
724 | /// Adds a delayed diagnostic. | |||
725 | void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h | |||
726 | ||||
727 | /// Determines whether diagnostics should be delayed. | |||
728 | bool shouldDelayDiagnostics() { return CurPool != nullptr; } | |||
729 | ||||
730 | /// Returns the current delayed-diagnostics pool. | |||
731 | sema::DelayedDiagnosticPool *getCurrentPool() const { | |||
732 | return CurPool; | |||
733 | } | |||
734 | ||||
735 | /// Enter a new scope. Access and deprecation diagnostics will be | |||
736 | /// collected in this pool. | |||
737 | DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { | |||
738 | DelayedDiagnosticsState state; | |||
739 | state.SavedPool = CurPool; | |||
740 | CurPool = &pool; | |||
741 | return state; | |||
742 | } | |||
743 | ||||
744 | /// Leave a delayed-diagnostic state that was previously pushed. | |||
745 | /// Do not emit any of the diagnostics. This is performed as part | |||
746 | /// of the bookkeeping of popping a pool "properly". | |||
747 | void popWithoutEmitting(DelayedDiagnosticsState state) { | |||
748 | CurPool = state.SavedPool; | |||
749 | } | |||
750 | ||||
751 | /// Enter a new scope where access and deprecation diagnostics are | |||
752 | /// not delayed. | |||
753 | DelayedDiagnosticsState pushUndelayed() { | |||
754 | DelayedDiagnosticsState state; | |||
755 | state.SavedPool = CurPool; | |||
756 | CurPool = nullptr; | |||
757 | return state; | |||
758 | } | |||
759 | ||||
760 | /// Undo a previous pushUndelayed(). | |||
761 | void popUndelayed(DelayedDiagnosticsState state) { | |||
762 | assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail ("CurPool == nullptr", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 762, __PRETTY_FUNCTION__)); | |||
763 | CurPool = state.SavedPool; | |||
764 | } | |||
765 | } DelayedDiagnostics; | |||
766 | ||||
767 | /// A RAII object to temporarily push a declaration context. | |||
768 | class ContextRAII { | |||
769 | private: | |||
770 | Sema &S; | |||
771 | DeclContext *SavedContext; | |||
772 | ProcessingContextState SavedContextState; | |||
773 | QualType SavedCXXThisTypeOverride; | |||
774 | ||||
775 | public: | |||
776 | ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) | |||
777 | : S(S), SavedContext(S.CurContext), | |||
778 | SavedContextState(S.DelayedDiagnostics.pushUndelayed()), | |||
779 | SavedCXXThisTypeOverride(S.CXXThisTypeOverride) | |||
780 | { | |||
781 | assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast <void> (0) : __assert_fail ("ContextToPush && \"pushing null context\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 781, __PRETTY_FUNCTION__)); | |||
782 | S.CurContext = ContextToPush; | |||
783 | if (NewThisContext) | |||
784 | S.CXXThisTypeOverride = QualType(); | |||
785 | } | |||
786 | ||||
787 | void pop() { | |||
788 | if (!SavedContext) return; | |||
789 | S.CurContext = SavedContext; | |||
790 | S.DelayedDiagnostics.popUndelayed(SavedContextState); | |||
791 | S.CXXThisTypeOverride = SavedCXXThisTypeOverride; | |||
792 | SavedContext = nullptr; | |||
793 | } | |||
794 | ||||
795 | ~ContextRAII() { | |||
796 | pop(); | |||
797 | } | |||
798 | }; | |||
799 | ||||
800 | /// RAII object to handle the state changes required to synthesize | |||
801 | /// a function body. | |||
802 | class SynthesizedFunctionScope { | |||
803 | Sema &S; | |||
804 | Sema::ContextRAII SavedContext; | |||
805 | bool PushedCodeSynthesisContext = false; | |||
806 | ||||
807 | public: | |||
808 | SynthesizedFunctionScope(Sema &S, DeclContext *DC) | |||
809 | : S(S), SavedContext(S, DC) { | |||
810 | S.PushFunctionScope(); | |||
811 | S.PushExpressionEvaluationContext( | |||
812 | Sema::ExpressionEvaluationContext::PotentiallyEvaluated); | |||
813 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) | |||
814 | FD->setWillHaveBody(true); | |||
815 | else | |||
816 | assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0 ) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 816, __PRETTY_FUNCTION__)); | |||
817 | } | |||
818 | ||||
819 | void addContextNote(SourceLocation UseLoc) { | |||
820 | assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 820, __PRETTY_FUNCTION__)); | |||
821 | ||||
822 | Sema::CodeSynthesisContext Ctx; | |||
823 | Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; | |||
824 | Ctx.PointOfInstantiation = UseLoc; | |||
825 | Ctx.Entity = cast<Decl>(S.CurContext); | |||
826 | S.pushCodeSynthesisContext(Ctx); | |||
| ||||
827 | ||||
828 | PushedCodeSynthesisContext = true; | |||
829 | } | |||
830 | ||||
831 | ~SynthesizedFunctionScope() { | |||
832 | if (PushedCodeSynthesisContext) | |||
833 | S.popCodeSynthesisContext(); | |||
834 | if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) | |||
835 | FD->setWillHaveBody(false); | |||
836 | S.PopExpressionEvaluationContext(); | |||
837 | S.PopFunctionScopeInfo(); | |||
838 | } | |||
839 | }; | |||
840 | ||||
841 | /// WeakUndeclaredIdentifiers - Identifiers contained in | |||
842 | /// \#pragma weak before declared. rare. may alias another | |||
843 | /// identifier, declared or undeclared | |||
844 | llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; | |||
845 | ||||
846 | /// ExtnameUndeclaredIdentifiers - Identifiers contained in | |||
847 | /// \#pragma redefine_extname before declared. Used in Solaris system headers | |||
848 | /// to define functions that occur in multiple standards to call the version | |||
849 | /// in the currently selected standard. | |||
850 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; | |||
851 | ||||
852 | ||||
853 | /// Load weak undeclared identifiers from the external source. | |||
854 | void LoadExternalWeakUndeclaredIdentifiers(); | |||
855 | ||||
856 | /// WeakTopLevelDecl - Translation-unit scoped declarations generated by | |||
857 | /// \#pragma weak during processing of other Decls. | |||
858 | /// I couldn't figure out a clean way to generate these in-line, so | |||
859 | /// we store them here and handle separately -- which is a hack. | |||
860 | /// It would be best to refactor this. | |||
861 | SmallVector<Decl*,2> WeakTopLevelDecl; | |||
862 | ||||
863 | IdentifierResolver IdResolver; | |||
864 | ||||
865 | /// Translation Unit Scope - useful to Objective-C actions that need | |||
866 | /// to lookup file scope declarations in the "ordinary" C decl namespace. | |||
867 | /// For example, user-defined classes, built-in "id" type, etc. | |||
868 | Scope *TUScope; | |||
869 | ||||
870 | /// The C++ "std" namespace, where the standard library resides. | |||
871 | LazyDeclPtr StdNamespace; | |||
872 | ||||
873 | /// The C++ "std::bad_alloc" class, which is defined by the C++ | |||
874 | /// standard library. | |||
875 | LazyDeclPtr StdBadAlloc; | |||
876 | ||||
877 | /// The C++ "std::align_val_t" enum class, which is defined by the C++ | |||
878 | /// standard library. | |||
879 | LazyDeclPtr StdAlignValT; | |||
880 | ||||
881 | /// The C++ "std::experimental" namespace, where the experimental parts | |||
882 | /// of the standard library resides. | |||
883 | NamespaceDecl *StdExperimentalNamespaceCache; | |||
884 | ||||
885 | /// The C++ "std::initializer_list" template, which is defined in | |||
886 | /// \<initializer_list>. | |||
887 | ClassTemplateDecl *StdInitializerList; | |||
888 | ||||
889 | /// The C++ "std::coroutine_traits" template, which is defined in | |||
890 | /// \<coroutine_traits> | |||
891 | ClassTemplateDecl *StdCoroutineTraitsCache; | |||
892 | ||||
893 | /// The C++ "type_info" declaration, which is defined in \<typeinfo>. | |||
894 | RecordDecl *CXXTypeInfoDecl; | |||
895 | ||||
896 | /// The MSVC "_GUID" struct, which is defined in MSVC header files. | |||
897 | RecordDecl *MSVCGuidDecl; | |||
898 | ||||
899 | /// Caches identifiers/selectors for NSFoundation APIs. | |||
900 | std::unique_ptr<NSAPI> NSAPIObj; | |||
901 | ||||
902 | /// The declaration of the Objective-C NSNumber class. | |||
903 | ObjCInterfaceDecl *NSNumberDecl; | |||
904 | ||||
905 | /// The declaration of the Objective-C NSValue class. | |||
906 | ObjCInterfaceDecl *NSValueDecl; | |||
907 | ||||
908 | /// Pointer to NSNumber type (NSNumber *). | |||
909 | QualType NSNumberPointer; | |||
910 | ||||
911 | /// Pointer to NSValue type (NSValue *). | |||
912 | QualType NSValuePointer; | |||
913 | ||||
914 | /// The Objective-C NSNumber methods used to create NSNumber literals. | |||
915 | ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; | |||
916 | ||||
917 | /// The declaration of the Objective-C NSString class. | |||
918 | ObjCInterfaceDecl *NSStringDecl; | |||
919 | ||||
920 | /// Pointer to NSString type (NSString *). | |||
921 | QualType NSStringPointer; | |||
922 | ||||
923 | /// The declaration of the stringWithUTF8String: method. | |||
924 | ObjCMethodDecl *StringWithUTF8StringMethod; | |||
925 | ||||
926 | /// The declaration of the valueWithBytes:objCType: method. | |||
927 | ObjCMethodDecl *ValueWithBytesObjCTypeMethod; | |||
928 | ||||
929 | /// The declaration of the Objective-C NSArray class. | |||
930 | ObjCInterfaceDecl *NSArrayDecl; | |||
931 | ||||
932 | /// The declaration of the arrayWithObjects:count: method. | |||
933 | ObjCMethodDecl *ArrayWithObjectsMethod; | |||
934 | ||||
935 | /// The declaration of the Objective-C NSDictionary class. | |||
936 | ObjCInterfaceDecl *NSDictionaryDecl; | |||
937 | ||||
938 | /// The declaration of the dictionaryWithObjects:forKeys:count: method. | |||
939 | ObjCMethodDecl *DictionaryWithObjectsMethod; | |||
940 | ||||
941 | /// id<NSCopying> type. | |||
942 | QualType QIDNSCopying; | |||
943 | ||||
944 | /// will hold 'respondsToSelector:' | |||
945 | Selector RespondsToSelectorSel; | |||
946 | ||||
947 | /// A flag to remember whether the implicit forms of operator new and delete | |||
948 | /// have been declared. | |||
949 | bool GlobalNewDeleteDeclared; | |||
950 | ||||
951 | /// A flag to indicate that we're in a context that permits abstract | |||
952 | /// references to fields. This is really a | |||
953 | bool AllowAbstractFieldReference; | |||
954 | ||||
955 | /// Describes how the expressions currently being parsed are | |||
956 | /// evaluated at run-time, if at all. | |||
957 | enum class ExpressionEvaluationContext { | |||
958 | /// The current expression and its subexpressions occur within an | |||
959 | /// unevaluated operand (C++11 [expr]p7), such as the subexpression of | |||
960 | /// \c sizeof, where the type of the expression may be significant but | |||
961 | /// no code will be generated to evaluate the value of the expression at | |||
962 | /// run time. | |||
963 | Unevaluated, | |||
964 | ||||
965 | /// The current expression occurs within a braced-init-list within | |||
966 | /// an unevaluated operand. This is mostly like a regular unevaluated | |||
967 | /// context, except that we still instantiate constexpr functions that are | |||
968 | /// referenced here so that we can perform narrowing checks correctly. | |||
969 | UnevaluatedList, | |||
970 | ||||
971 | /// The current expression occurs within a discarded statement. | |||
972 | /// This behaves largely similarly to an unevaluated operand in preventing | |||
973 | /// definitions from being required, but not in other ways. | |||
974 | DiscardedStatement, | |||
975 | ||||
976 | /// The current expression occurs within an unevaluated | |||
977 | /// operand that unconditionally permits abstract references to | |||
978 | /// fields, such as a SIZE operator in MS-style inline assembly. | |||
979 | UnevaluatedAbstract, | |||
980 | ||||
981 | /// The current context is "potentially evaluated" in C++11 terms, | |||
982 | /// but the expression is evaluated at compile-time (like the values of | |||
983 | /// cases in a switch statement). | |||
984 | ConstantEvaluated, | |||
985 | ||||
986 | /// The current expression is potentially evaluated at run time, | |||
987 | /// which means that code may be generated to evaluate the value of the | |||
988 | /// expression at run time. | |||
989 | PotentiallyEvaluated, | |||
990 | ||||
991 | /// The current expression is potentially evaluated, but any | |||
992 | /// declarations referenced inside that expression are only used if | |||
993 | /// in fact the current expression is used. | |||
994 | /// | |||
995 | /// This value is used when parsing default function arguments, for which | |||
996 | /// we would like to provide diagnostics (e.g., passing non-POD arguments | |||
997 | /// through varargs) but do not want to mark declarations as "referenced" | |||
998 | /// until the default argument is used. | |||
999 | PotentiallyEvaluatedIfUsed | |||
1000 | }; | |||
1001 | ||||
1002 | /// Data structure used to record current or nested | |||
1003 | /// expression evaluation contexts. | |||
1004 | struct ExpressionEvaluationContextRecord { | |||
1005 | /// The expression evaluation context. | |||
1006 | ExpressionEvaluationContext Context; | |||
1007 | ||||
1008 | /// Whether the enclosing context needed a cleanup. | |||
1009 | CleanupInfo ParentCleanup; | |||
1010 | ||||
1011 | /// Whether we are in a decltype expression. | |||
1012 | bool IsDecltype; | |||
1013 | ||||
1014 | /// The number of active cleanup objects when we entered | |||
1015 | /// this expression evaluation context. | |||
1016 | unsigned NumCleanupObjects; | |||
1017 | ||||
1018 | /// The number of typos encountered during this expression evaluation | |||
1019 | /// context (i.e. the number of TypoExprs created). | |||
1020 | unsigned NumTypos; | |||
1021 | ||||
1022 | MaybeODRUseExprSet SavedMaybeODRUseExprs; | |||
1023 | ||||
1024 | /// The lambdas that are present within this context, if it | |||
1025 | /// is indeed an unevaluated context. | |||
1026 | SmallVector<LambdaExpr *, 2> Lambdas; | |||
1027 | ||||
1028 | /// The declaration that provides context for lambda expressions | |||
1029 | /// and block literals if the normal declaration context does not | |||
1030 | /// suffice, e.g., in a default function argument. | |||
1031 | Decl *ManglingContextDecl; | |||
1032 | ||||
1033 | /// The context information used to mangle lambda expressions | |||
1034 | /// and block literals within this context. | |||
1035 | /// | |||
1036 | /// This mangling information is allocated lazily, since most contexts | |||
1037 | /// do not have lambda expressions or block literals. | |||
1038 | std::unique_ptr<MangleNumberingContext> MangleNumbering; | |||
1039 | ||||
1040 | /// If we are processing a decltype type, a set of call expressions | |||
1041 | /// for which we have deferred checking the completeness of the return type. | |||
1042 | SmallVector<CallExpr *, 8> DelayedDecltypeCalls; | |||
1043 | ||||
1044 | /// If we are processing a decltype type, a set of temporary binding | |||
1045 | /// expressions for which we have deferred checking the destructor. | |||
1046 | SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; | |||
1047 | ||||
1048 | llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; | |||
1049 | ||||
1050 | /// \brief Describes whether we are in an expression constext which we have | |||
1051 | /// to handle differently. | |||
1052 | enum ExpressionKind { | |||
1053 | EK_Decltype, EK_TemplateArgument, EK_Other | |||
1054 | } ExprContext; | |||
1055 | ||||
1056 | ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, | |||
1057 | unsigned NumCleanupObjects, | |||
1058 | CleanupInfo ParentCleanup, | |||
1059 | Decl *ManglingContextDecl, | |||
1060 | ExpressionKind ExprContext) | |||
1061 | : Context(Context), ParentCleanup(ParentCleanup), | |||
1062 | NumCleanupObjects(NumCleanupObjects), NumTypos(0), | |||
1063 | ManglingContextDecl(ManglingContextDecl), MangleNumbering(), | |||
1064 | ExprContext(ExprContext) {} | |||
1065 | ||||
1066 | /// Retrieve the mangling numbering context, used to consistently | |||
1067 | /// number constructs like lambdas for mangling. | |||
1068 | MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); | |||
1069 | ||||
1070 | bool isUnevaluated() const { | |||
1071 | return Context == ExpressionEvaluationContext::Unevaluated || | |||
1072 | Context == ExpressionEvaluationContext::UnevaluatedAbstract || | |||
1073 | Context == ExpressionEvaluationContext::UnevaluatedList; | |||
1074 | } | |||
1075 | bool isConstantEvaluated() const { | |||
1076 | return Context == ExpressionEvaluationContext::ConstantEvaluated; | |||
1077 | } | |||
1078 | }; | |||
1079 | ||||
1080 | /// A stack of expression evaluation contexts. | |||
1081 | SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; | |||
1082 | ||||
1083 | /// Emit a warning for all pending noderef expressions that we recorded. | |||
1084 | void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); | |||
1085 | ||||
1086 | /// Compute the mangling number context for a lambda expression or | |||
1087 | /// block literal. | |||
1088 | /// | |||
1089 | /// \param DC - The DeclContext containing the lambda expression or | |||
1090 | /// block literal. | |||
1091 | /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl | |||
1092 | /// associated with the context, if relevant. | |||
1093 | MangleNumberingContext *getCurrentMangleNumberContext( | |||
1094 | const DeclContext *DC, | |||
1095 | Decl *&ManglingContextDecl); | |||
1096 | ||||
1097 | ||||
1098 | /// SpecialMemberOverloadResult - The overloading result for a special member | |||
1099 | /// function. | |||
1100 | /// | |||
1101 | /// This is basically a wrapper around PointerIntPair. The lowest bits of the | |||
1102 | /// integer are used to determine whether overload resolution succeeded. | |||
1103 | class SpecialMemberOverloadResult { | |||
1104 | public: | |||
1105 | enum Kind { | |||
1106 | NoMemberOrDeleted, | |||
1107 | Ambiguous, | |||
1108 | Success | |||
1109 | }; | |||
1110 | ||||
1111 | private: | |||
1112 | llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; | |||
1113 | ||||
1114 | public: | |||
1115 | SpecialMemberOverloadResult() : Pair() {} | |||
1116 | SpecialMemberOverloadResult(CXXMethodDecl *MD) | |||
1117 | : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} | |||
1118 | ||||
1119 | CXXMethodDecl *getMethod() const { return Pair.getPointer(); } | |||
1120 | void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } | |||
1121 | ||||
1122 | Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } | |||
1123 | void setKind(Kind K) { Pair.setInt(K); } | |||
1124 | }; | |||
1125 | ||||
1126 | class SpecialMemberOverloadResultEntry | |||
1127 | : public llvm::FastFoldingSetNode, | |||
1128 | public SpecialMemberOverloadResult { | |||
1129 | public: | |||
1130 | SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) | |||
1131 | : FastFoldingSetNode(ID) | |||
1132 | {} | |||
1133 | }; | |||
1134 | ||||
1135 | /// A cache of special member function overload resolution results | |||
1136 | /// for C++ records. | |||
1137 | llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; | |||
1138 | ||||
1139 | /// A cache of the flags available in enumerations with the flag_bits | |||
1140 | /// attribute. | |||
1141 | mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; | |||
1142 | ||||
1143 | /// The kind of translation unit we are processing. | |||
1144 | /// | |||
1145 | /// When we're processing a complete translation unit, Sema will perform | |||
1146 | /// end-of-translation-unit semantic tasks (such as creating | |||
1147 | /// initializers for tentative definitions in C) once parsing has | |||
1148 | /// completed. Modules and precompiled headers perform different kinds of | |||
1149 | /// checks. | |||
1150 | TranslationUnitKind TUKind; | |||
1151 | ||||
1152 | llvm::BumpPtrAllocator BumpAlloc; | |||
1153 | ||||
1154 | /// The number of SFINAE diagnostics that have been trapped. | |||
1155 | unsigned NumSFINAEErrors; | |||
1156 | ||||
1157 | typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> | |||
1158 | UnparsedDefaultArgInstantiationsMap; | |||
1159 | ||||
1160 | /// A mapping from parameters with unparsed default arguments to the | |||
1161 | /// set of instantiations of each parameter. | |||
1162 | /// | |||
1163 | /// This mapping is a temporary data structure used when parsing | |||
1164 | /// nested class templates or nested classes of class templates, | |||
1165 | /// where we might end up instantiating an inner class before the | |||
1166 | /// default arguments of its methods have been parsed. | |||
1167 | UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; | |||
1168 | ||||
1169 | // Contains the locations of the beginning of unparsed default | |||
1170 | // argument locations. | |||
1171 | llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; | |||
1172 | ||||
1173 | /// UndefinedInternals - all the used, undefined objects which require a | |||
1174 | /// definition in this translation unit. | |||
1175 | llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; | |||
1176 | ||||
1177 | /// Determine if VD, which must be a variable or function, is an external | |||
1178 | /// symbol that nonetheless can't be referenced from outside this translation | |||
1179 | /// unit because its type has no linkage and it's not extern "C". | |||
1180 | bool isExternalWithNoLinkageType(ValueDecl *VD); | |||
1181 | ||||
1182 | /// Obtain a sorted list of functions that are undefined but ODR-used. | |||
1183 | void getUndefinedButUsed( | |||
1184 | SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); | |||
1185 | ||||
1186 | /// Retrieves list of suspicious delete-expressions that will be checked at | |||
1187 | /// the end of translation unit. | |||
1188 | const llvm::MapVector<FieldDecl *, DeleteLocs> & | |||
1189 | getMismatchingDeleteExpressions() const; | |||
1190 | ||||
1191 | typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; | |||
1192 | typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; | |||
1193 | ||||
1194 | /// Method Pool - allows efficient lookup when typechecking messages to "id". | |||
1195 | /// We need to maintain a list, since selectors can have differing signatures | |||
1196 | /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% | |||
1197 | /// of selectors are "overloaded"). | |||
1198 | /// At the head of the list it is recorded whether there were 0, 1, or >= 2 | |||
1199 | /// methods inside categories with a particular selector. | |||
1200 | GlobalMethodPool MethodPool; | |||
1201 | ||||
1202 | /// Method selectors used in a \@selector expression. Used for implementation | |||
1203 | /// of -Wselector. | |||
1204 | llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; | |||
1205 | ||||
1206 | /// List of SourceLocations where 'self' is implicitly retained inside a | |||
1207 | /// block. | |||
1208 | llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> | |||
1209 | ImplicitlyRetainedSelfLocs; | |||
1210 | ||||
1211 | /// Kinds of C++ special members. | |||
1212 | enum CXXSpecialMember { | |||
1213 | CXXDefaultConstructor, | |||
1214 | CXXCopyConstructor, | |||
1215 | CXXMoveConstructor, | |||
1216 | CXXCopyAssignment, | |||
1217 | CXXMoveAssignment, | |||
1218 | CXXDestructor, | |||
1219 | CXXInvalid | |||
1220 | }; | |||
1221 | ||||
1222 | typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> | |||
1223 | SpecialMemberDecl; | |||
1224 | ||||
1225 | /// The C++ special members which we are currently in the process of | |||
1226 | /// declaring. If this process recursively triggers the declaration of the | |||
1227 | /// same special member, we should act as if it is not yet declared. | |||
1228 | llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; | |||
1229 | ||||
1230 | /// The function definitions which were renamed as part of typo-correction | |||
1231 | /// to match their respective declarations. We want to keep track of them | |||
1232 | /// to ensure that we don't emit a "redefinition" error if we encounter a | |||
1233 | /// correctly named definition after the renamed definition. | |||
1234 | llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; | |||
1235 | ||||
1236 | /// Stack of types that correspond to the parameter entities that are | |||
1237 | /// currently being copy-initialized. Can be empty. | |||
1238 | llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; | |||
1239 | ||||
1240 | void ReadMethodPool(Selector Sel); | |||
1241 | void updateOutOfDateSelector(Selector Sel); | |||
1242 | ||||
1243 | /// Private Helper predicate to check for 'self'. | |||
1244 | bool isSelfExpr(Expr *RExpr); | |||
1245 | bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); | |||
1246 | ||||
1247 | /// Cause the active diagnostic on the DiagosticsEngine to be | |||
1248 | /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and | |||
1249 | /// should not be used elsewhere. | |||
1250 | void EmitCurrentDiagnostic(unsigned DiagID); | |||
1251 | ||||
1252 | /// Records and restores the FP_CONTRACT state on entry/exit of compound | |||
1253 | /// statements. | |||
1254 | class FPContractStateRAII { | |||
1255 | public: | |||
1256 | FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} | |||
1257 | ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } | |||
1258 | ||||
1259 | private: | |||
1260 | Sema& S; | |||
1261 | FPOptions OldFPFeaturesState; | |||
1262 | }; | |||
1263 | ||||
1264 | void addImplicitTypedef(StringRef Name, QualType T); | |||
1265 | ||||
1266 | public: | |||
1267 | Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, | |||
1268 | TranslationUnitKind TUKind = TU_Complete, | |||
1269 | CodeCompleteConsumer *CompletionConsumer = nullptr); | |||
1270 | ~Sema(); | |||
1271 | ||||
1272 | /// Perform initialization that occurs after the parser has been | |||
1273 | /// initialized but before it parses anything. | |||
1274 | void Initialize(); | |||
1275 | ||||
1276 | const LangOptions &getLangOpts() const { return LangOpts; } | |||
1277 | OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } | |||
1278 | FPOptions &getFPOptions() { return FPFeatures; } | |||
1279 | ||||
1280 | DiagnosticsEngine &getDiagnostics() const { return Diags; } | |||
1281 | SourceManager &getSourceManager() const { return SourceMgr; } | |||
1282 | Preprocessor &getPreprocessor() const { return PP; } | |||
1283 | ASTContext &getASTContext() const { return Context; } | |||
1284 | ASTConsumer &getASTConsumer() const { return Consumer; } | |||
1285 | ASTMutationListener *getASTMutationListener() const; | |||
1286 | ExternalSemaSource* getExternalSource() const { return ExternalSource; } | |||
1287 | ||||
1288 | ///Registers an external source. If an external source already exists, | |||
1289 | /// creates a multiplex external source and appends to it. | |||
1290 | /// | |||
1291 | ///\param[in] E - A non-null external sema source. | |||
1292 | /// | |||
1293 | void addExternalSource(ExternalSemaSource *E); | |||
1294 | ||||
1295 | void PrintStats() const; | |||
1296 | ||||
1297 | /// Helper class that creates diagnostics with optional | |||
1298 | /// template instantiation stacks. | |||
1299 | /// | |||
1300 | /// This class provides a wrapper around the basic DiagnosticBuilder | |||
1301 | /// class that emits diagnostics. SemaDiagnosticBuilder is | |||
1302 | /// responsible for emitting the diagnostic (as DiagnosticBuilder | |||
1303 | /// does) and, if the diagnostic comes from inside a template | |||
1304 | /// instantiation, printing the template instantiation stack as | |||
1305 | /// well. | |||
1306 | class SemaDiagnosticBuilder : public DiagnosticBuilder { | |||
1307 | Sema &SemaRef; | |||
1308 | unsigned DiagID; | |||
1309 | ||||
1310 | public: | |||
1311 | SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) | |||
1312 | : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } | |||
1313 | ||||
1314 | // This is a cunning lie. DiagnosticBuilder actually performs move | |||
1315 | // construction in its copy constructor (but due to varied uses, it's not | |||
1316 | // possible to conveniently express this as actual move construction). So | |||
1317 | // the default copy ctor here is fine, because the base class disables the | |||
1318 | // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op | |||
1319 | // in that case anwyay. | |||
1320 | SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; | |||
1321 | ||||
1322 | ~SemaDiagnosticBuilder() { | |||
1323 | // If we aren't active, there is nothing to do. | |||
1324 | if (!isActive()) return; | |||
1325 | ||||
1326 | // Otherwise, we need to emit the diagnostic. First flush the underlying | |||
1327 | // DiagnosticBuilder data, and clear the diagnostic builder itself so it | |||
1328 | // won't emit the diagnostic in its own destructor. | |||
1329 | // | |||
1330 | // This seems wasteful, in that as written the DiagnosticBuilder dtor will | |||
1331 | // do its own needless checks to see if the diagnostic needs to be | |||
1332 | // emitted. However, because we take care to ensure that the builder | |||
1333 | // objects never escape, a sufficiently smart compiler will be able to | |||
1334 | // eliminate that code. | |||
1335 | FlushCounts(); | |||
1336 | Clear(); | |||
1337 | ||||
1338 | // Dispatch to Sema to emit the diagnostic. | |||
1339 | SemaRef.EmitCurrentDiagnostic(DiagID); | |||
1340 | } | |||
1341 | ||||
1342 | /// Teach operator<< to produce an object of the correct type. | |||
1343 | template<typename T> | |||
1344 | friend const SemaDiagnosticBuilder &operator<<( | |||
1345 | const SemaDiagnosticBuilder &Diag, const T &Value) { | |||
1346 | const DiagnosticBuilder &BaseDiag = Diag; | |||
1347 | BaseDiag << Value; | |||
1348 | return Diag; | |||
1349 | } | |||
1350 | }; | |||
1351 | ||||
1352 | /// Emit a diagnostic. | |||
1353 | SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { | |||
1354 | DiagnosticBuilder DB = Diags.Report(Loc, DiagID); | |||
1355 | return SemaDiagnosticBuilder(DB, *this, DiagID); | |||
1356 | } | |||
1357 | ||||
1358 | /// Emit a partial diagnostic. | |||
1359 | SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); | |||
1360 | ||||
1361 | /// Build a partial diagnostic. | |||
1362 | PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h | |||
1363 | ||||
1364 | bool findMacroSpelling(SourceLocation &loc, StringRef name); | |||
1365 | ||||
1366 | /// Get a string to suggest for zero-initialization of a type. | |||
1367 | std::string | |||
1368 | getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; | |||
1369 | std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; | |||
1370 | ||||
1371 | /// Calls \c Lexer::getLocForEndOfToken() | |||
1372 | SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); | |||
1373 | ||||
1374 | /// Retrieve the module loader associated with the preprocessor. | |||
1375 | ModuleLoader &getModuleLoader() const; | |||
1376 | ||||
1377 | void emitAndClearUnusedLocalTypedefWarnings(); | |||
1378 | ||||
1379 | enum TUFragmentKind { | |||
1380 | /// The global module fragment, between 'module;' and a module-declaration. | |||
1381 | Global, | |||
1382 | /// A normal translation unit fragment. For a non-module unit, this is the | |||
1383 | /// entire translation unit. Otherwise, it runs from the module-declaration | |||
1384 | /// to the private-module-fragment (if any) or the end of the TU (if not). | |||
1385 | Normal, | |||
1386 | /// The private module fragment, between 'module :private;' and the end of | |||
1387 | /// the translation unit. | |||
1388 | Private | |||
1389 | }; | |||
1390 | ||||
1391 | void ActOnStartOfTranslationUnit(); | |||
1392 | void ActOnEndOfTranslationUnit(); | |||
1393 | void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); | |||
1394 | ||||
1395 | void CheckDelegatingCtorCycles(); | |||
1396 | ||||
1397 | Scope *getScopeForContext(DeclContext *Ctx); | |||
1398 | ||||
1399 | void PushFunctionScope(); | |||
1400 | void PushBlockScope(Scope *BlockScope, BlockDecl *Block); | |||
1401 | sema::LambdaScopeInfo *PushLambdaScope(); | |||
1402 | ||||
1403 | /// This is used to inform Sema what the current TemplateParameterDepth | |||
1404 | /// is during Parsing. Currently it is used to pass on the depth | |||
1405 | /// when parsing generic lambda 'auto' parameters. | |||
1406 | void RecordParsingTemplateParameterDepth(unsigned Depth); | |||
1407 | ||||
1408 | void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, | |||
1409 | RecordDecl *RD, | |||
1410 | CapturedRegionKind K); | |||
1411 | void | |||
1412 | PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, | |||
1413 | const Decl *D = nullptr, | |||
1414 | const BlockExpr *blkExpr = nullptr); | |||
1415 | ||||
1416 | sema::FunctionScopeInfo *getCurFunction() const { | |||
1417 | return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); | |||
1418 | } | |||
1419 | ||||
1420 | sema::FunctionScopeInfo *getEnclosingFunction() const; | |||
1421 | ||||
1422 | void setFunctionHasBranchIntoScope(); | |||
1423 | void setFunctionHasBranchProtectedScope(); | |||
1424 | void setFunctionHasIndirectGoto(); | |||
1425 | ||||
1426 | void PushCompoundScope(bool IsStmtExpr); | |||
1427 | void PopCompoundScope(); | |||
1428 | ||||
1429 | sema::CompoundScopeInfo &getCurCompoundScope() const; | |||
1430 | ||||
1431 | bool hasAnyUnrecoverableErrorsInThisFunction() const; | |||
1432 | ||||
1433 | /// Retrieve the current block, if any. | |||
1434 | sema::BlockScopeInfo *getCurBlock(); | |||
1435 | ||||
1436 | /// Retrieve the current lambda scope info, if any. | |||
1437 | /// \param IgnoreNonLambdaCapturingScope true if should find the top-most | |||
1438 | /// lambda scope info ignoring all inner capturing scopes that are not | |||
1439 | /// lambda scopes. | |||
1440 | sema::LambdaScopeInfo * | |||
1441 | getCurLambda(bool IgnoreNonLambdaCapturingScope = false); | |||
1442 | ||||
1443 | /// Retrieve the current generic lambda info, if any. | |||
1444 | sema::LambdaScopeInfo *getCurGenericLambda(); | |||
1445 | ||||
1446 | /// Retrieve the current captured region, if any. | |||
1447 | sema::CapturedRegionScopeInfo *getCurCapturedRegion(); | |||
1448 | ||||
1449 | /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls | |||
1450 | SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } | |||
1451 | ||||
1452 | void ActOnComment(SourceRange Comment); | |||
1453 | ||||
1454 | //===--------------------------------------------------------------------===// | |||
1455 | // Type Analysis / Processing: SemaType.cpp. | |||
1456 | // | |||
1457 | ||||
1458 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, | |||
1459 | const DeclSpec *DS = nullptr); | |||
1460 | QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, | |||
1461 | const DeclSpec *DS = nullptr); | |||
1462 | QualType BuildPointerType(QualType T, | |||
1463 | SourceLocation Loc, DeclarationName Entity); | |||
1464 | QualType BuildReferenceType(QualType T, bool LValueRef, | |||
1465 | SourceLocation Loc, DeclarationName Entity); | |||
1466 | QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, | |||
1467 | Expr *ArraySize, unsigned Quals, | |||
1468 | SourceRange Brackets, DeclarationName Entity); | |||
1469 | QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); | |||
1470 | QualType BuildExtVectorType(QualType T, Expr *ArraySize, | |||
1471 | SourceLocation AttrLoc); | |||
1472 | QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, | |||
1473 | SourceLocation AttrLoc); | |||
1474 | ||||
1475 | /// Same as above, but constructs the AddressSpace index if not provided. | |||
1476 | QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, | |||
1477 | SourceLocation AttrLoc); | |||
1478 | ||||
1479 | bool CheckFunctionReturnType(QualType T, SourceLocation Loc); | |||
1480 | ||||
1481 | /// Build a function type. | |||
1482 | /// | |||
1483 | /// This routine checks the function type according to C++ rules and | |||
1484 | /// under the assumption that the result type and parameter types have | |||
1485 | /// just been instantiated from a template. It therefore duplicates | |||
1486 | /// some of the behavior of GetTypeForDeclarator, but in a much | |||
1487 | /// simpler form that is only suitable for this narrow use case. | |||
1488 | /// | |||
1489 | /// \param T The return type of the function. | |||
1490 | /// | |||
1491 | /// \param ParamTypes The parameter types of the function. This array | |||
1492 | /// will be modified to account for adjustments to the types of the | |||
1493 | /// function parameters. | |||
1494 | /// | |||
1495 | /// \param Loc The location of the entity whose type involves this | |||
1496 | /// function type or, if there is no such entity, the location of the | |||
1497 | /// type that will have function type. | |||
1498 | /// | |||
1499 | /// \param Entity The name of the entity that involves the function | |||
1500 | /// type, if known. | |||
1501 | /// | |||
1502 | /// \param EPI Extra information about the function type. Usually this will | |||
1503 | /// be taken from an existing function with the same prototype. | |||
1504 | /// | |||
1505 | /// \returns A suitable function type, if there are no errors. The | |||
1506 | /// unqualified type will always be a FunctionProtoType. | |||
1507 | /// Otherwise, returns a NULL type. | |||
1508 | QualType BuildFunctionType(QualType T, | |||
1509 | MutableArrayRef<QualType> ParamTypes, | |||
1510 | SourceLocation Loc, DeclarationName Entity, | |||
1511 | const FunctionProtoType::ExtProtoInfo &EPI); | |||
1512 | ||||
1513 | QualType BuildMemberPointerType(QualType T, QualType Class, | |||
1514 | SourceLocation Loc, | |||
1515 | DeclarationName Entity); | |||
1516 | QualType BuildBlockPointerType(QualType T, | |||
1517 | SourceLocation Loc, DeclarationName Entity); | |||
1518 | QualType BuildParenType(QualType T); | |||
1519 | QualType BuildAtomicType(QualType T, SourceLocation Loc); | |||
1520 | QualType BuildReadPipeType(QualType T, | |||
1521 | SourceLocation Loc); | |||
1522 | QualType BuildWritePipeType(QualType T, | |||
1523 | SourceLocation Loc); | |||
1524 | ||||
1525 | TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); | |||
1526 | TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); | |||
1527 | ||||
1528 | /// Package the given type and TSI into a ParsedType. | |||
1529 | ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); | |||
1530 | DeclarationNameInfo GetNameForDeclarator(Declarator &D); | |||
1531 | DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); | |||
1532 | static QualType GetTypeFromParser(ParsedType Ty, | |||
1533 | TypeSourceInfo **TInfo = nullptr); | |||
1534 | CanThrowResult canThrow(const Expr *E); | |||
1535 | const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, | |||
1536 | const FunctionProtoType *FPT); | |||
1537 | void UpdateExceptionSpec(FunctionDecl *FD, | |||
1538 | const FunctionProtoType::ExceptionSpecInfo &ESI); | |||
1539 | bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); | |||
1540 | bool CheckDistantExceptionSpec(QualType T); | |||
1541 | bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); | |||
1542 | bool CheckEquivalentExceptionSpec( | |||
1543 | const FunctionProtoType *Old, SourceLocation OldLoc, | |||
1544 | const FunctionProtoType *New, SourceLocation NewLoc); | |||
1545 | bool CheckEquivalentExceptionSpec( | |||
1546 | const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, | |||
1547 | const FunctionProtoType *Old, SourceLocation OldLoc, | |||
1548 | const FunctionProtoType *New, SourceLocation NewLoc); | |||
1549 | bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); | |||
1550 | bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, | |||
1551 | const PartialDiagnostic &NestedDiagID, | |||
1552 | const PartialDiagnostic &NoteID, | |||
1553 | const FunctionProtoType *Superset, | |||
1554 | SourceLocation SuperLoc, | |||
1555 | const FunctionProtoType *Subset, | |||
1556 | SourceLocation SubLoc); | |||
1557 | bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, | |||
1558 | const PartialDiagnostic &NoteID, | |||
1559 | const FunctionProtoType *Target, | |||
1560 | SourceLocation TargetLoc, | |||
1561 | const FunctionProtoType *Source, | |||
1562 | SourceLocation SourceLoc); | |||
1563 | ||||
1564 | TypeResult ActOnTypeName(Scope *S, Declarator &D); | |||
1565 | ||||
1566 | /// The parser has parsed the context-sensitive type 'instancetype' | |||
1567 | /// in an Objective-C message declaration. Return the appropriate type. | |||
1568 | ParsedType ActOnObjCInstanceType(SourceLocation Loc); | |||
1569 | ||||
1570 | /// Abstract class used to diagnose incomplete types. | |||
1571 | struct TypeDiagnoser { | |||
1572 | TypeDiagnoser() {} | |||
1573 | ||||
1574 | virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; | |||
1575 | virtual ~TypeDiagnoser() {} | |||
1576 | }; | |||
1577 | ||||
1578 | static int getPrintable(int I) { return I; } | |||
1579 | static unsigned getPrintable(unsigned I) { return I; } | |||
1580 | static bool getPrintable(bool B) { return B; } | |||
1581 | static const char * getPrintable(const char *S) { return S; } | |||
1582 | static StringRef getPrintable(StringRef S) { return S; } | |||
1583 | static const std::string &getPrintable(const std::string &S) { return S; } | |||
1584 | static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { | |||
1585 | return II; | |||
1586 | } | |||
1587 | static DeclarationName getPrintable(DeclarationName N) { return N; } | |||
1588 | static QualType getPrintable(QualType T) { return T; } | |||
1589 | static SourceRange getPrintable(SourceRange R) { return R; } | |||
1590 | static SourceRange getPrintable(SourceLocation L) { return L; } | |||
1591 | static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } | |||
1592 | static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} | |||
1593 | ||||
1594 | template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { | |||
1595 | unsigned DiagID; | |||
1596 | std::tuple<const Ts &...> Args; | |||
1597 | ||||
1598 | template <std::size_t... Is> | |||
1599 | void emit(const SemaDiagnosticBuilder &DB, | |||
1600 | llvm::index_sequence<Is...>) const { | |||
1601 | // Apply all tuple elements to the builder in order. | |||
1602 | bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; | |||
1603 | (void)Dummy; | |||
1604 | } | |||
1605 | ||||
1606 | public: | |||
1607 | BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) | |||
1608 | : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { | |||
1609 | assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ? static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 1609, __PRETTY_FUNCTION__)); | |||
1610 | } | |||
1611 | ||||
1612 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { | |||
1613 | const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); | |||
1614 | emit(DB, llvm::index_sequence_for<Ts...>()); | |||
1615 | DB << T; | |||
1616 | } | |||
1617 | }; | |||
1618 | ||||
1619 | private: | |||
1620 | /// Methods for marking which expressions involve dereferencing a pointer | |||
1621 | /// marked with the 'noderef' attribute. Expressions are checked bottom up as | |||
1622 | /// they are parsed, meaning that a noderef pointer may not be accessed. For | |||
1623 | /// example, in `&*p` where `p` is a noderef pointer, we will first parse the | |||
1624 | /// `*p`, but need to check that `address of` is called on it. This requires | |||
1625 | /// keeping a container of all pending expressions and checking if the address | |||
1626 | /// of them are eventually taken. | |||
1627 | void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); | |||
1628 | void CheckAddressOfNoDeref(const Expr *E); | |||
1629 | void CheckMemberAccessOfNoDeref(const MemberExpr *E); | |||
1630 | ||||
1631 | bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, | |||
1632 | TypeDiagnoser *Diagnoser); | |||
1633 | ||||
1634 | struct ModuleScope { | |||
1635 | SourceLocation BeginLoc; | |||
1636 | clang::Module *Module = nullptr; | |||
1637 | bool ModuleInterface = false; | |||
1638 | bool ImplicitGlobalModuleFragment = false; | |||
1639 | VisibleModuleSet OuterVisibleModules; | |||
1640 | }; | |||
1641 | /// The modules we're currently parsing. | |||
1642 | llvm::SmallVector<ModuleScope, 16> ModuleScopes; | |||
1643 | ||||
1644 | /// Namespace definitions that we will export when they finish. | |||
1645 | llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; | |||
1646 | ||||
1647 | /// Get the module whose scope we are currently within. | |||
1648 | Module *getCurrentModule() const { | |||
1649 | return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; | |||
1650 | } | |||
1651 | ||||
1652 | VisibleModuleSet VisibleModules; | |||
1653 | ||||
1654 | public: | |||
1655 | /// Get the module owning an entity. | |||
1656 | Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } | |||
1657 | ||||
1658 | /// Make a merged definition of an existing hidden definition \p ND | |||
1659 | /// visible at the specified location. | |||
1660 | void makeMergedDefinitionVisible(NamedDecl *ND); | |||
1661 | ||||
1662 | bool isModuleVisible(const Module *M, bool ModulePrivate = false); | |||
1663 | ||||
1664 | /// Determine whether a declaration is visible to name lookup. | |||
1665 | bool isVisible(const NamedDecl *D) { | |||
1666 | return !D->isHidden() || isVisibleSlow(D); | |||
1667 | } | |||
1668 | ||||
1669 | /// Determine whether any declaration of an entity is visible. | |||
1670 | bool | |||
1671 | hasVisibleDeclaration(const NamedDecl *D, | |||
1672 | llvm::SmallVectorImpl<Module *> *Modules = nullptr) { | |||
1673 | return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); | |||
1674 | } | |||
1675 | bool hasVisibleDeclarationSlow(const NamedDecl *D, | |||
1676 | llvm::SmallVectorImpl<Module *> *Modules); | |||
1677 | ||||
1678 | bool hasVisibleMergedDefinition(NamedDecl *Def); | |||
1679 | bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); | |||
1680 | ||||
1681 | /// Determine if \p D and \p Suggested have a structurally compatible | |||
1682 | /// layout as described in C11 6.2.7/1. | |||
1683 | bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); | |||
1684 | ||||
1685 | /// Determine if \p D has a visible definition. If not, suggest a declaration | |||
1686 | /// that should be made visible to expose the definition. | |||
1687 | bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, | |||
1688 | bool OnlyNeedComplete = false); | |||
1689 | bool hasVisibleDefinition(const NamedDecl *D) { | |||
1690 | NamedDecl *Hidden; | |||
1691 | return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); | |||
1692 | } | |||
1693 | ||||
1694 | /// Determine if the template parameter \p D has a visible default argument. | |||
1695 | bool | |||
1696 | hasVisibleDefaultArgument(const NamedDecl *D, | |||
1697 | llvm::SmallVectorImpl<Module *> *Modules = nullptr); | |||
1698 | ||||
1699 | /// Determine if there is a visible declaration of \p D that is an explicit | |||
1700 | /// specialization declaration for a specialization of a template. (For a | |||
1701 | /// member specialization, use hasVisibleMemberSpecialization.) | |||
1702 | bool hasVisibleExplicitSpecialization( | |||
1703 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); | |||
1704 | ||||
1705 | /// Determine if there is a visible declaration of \p D that is a member | |||
1706 | /// specialization declaration (as opposed to an instantiated declaration). | |||
1707 | bool hasVisibleMemberSpecialization( | |||
1708 | const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); | |||
1709 | ||||
1710 | /// Determine if \p A and \p B are equivalent internal linkage declarations | |||
1711 | /// from different modules, and thus an ambiguity error can be downgraded to | |||
1712 | /// an extension warning. | |||
1713 | bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, | |||
1714 | const NamedDecl *B); | |||
1715 | void diagnoseEquivalentInternalLinkageDeclarations( | |||
1716 | SourceLocation Loc, const NamedDecl *D, | |||
1717 | ArrayRef<const NamedDecl *> Equiv); | |||
1718 | ||||
1719 | bool isUsualDeallocationFunction(const CXXMethodDecl *FD); | |||
1720 | ||||
1721 | bool isCompleteType(SourceLocation Loc, QualType T) { | |||
1722 | return !RequireCompleteTypeImpl(Loc, T, nullptr); | |||
1723 | } | |||
1724 | bool RequireCompleteType(SourceLocation Loc, QualType T, | |||
1725 | TypeDiagnoser &Diagnoser); | |||
1726 | bool RequireCompleteType(SourceLocation Loc, QualType T, | |||
1727 | unsigned DiagID); | |||
1728 | ||||
1729 | template <typename... Ts> | |||
1730 | bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, | |||
1731 | const Ts &...Args) { | |||
1732 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); | |||
1733 | return RequireCompleteType(Loc, T, Diagnoser); | |||
1734 | } | |||
1735 | ||||
1736 | void completeExprArrayBound(Expr *E); | |||
1737 | bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); | |||
1738 | bool RequireCompleteExprType(Expr *E, unsigned DiagID); | |||
1739 | ||||
1740 | template <typename... Ts> | |||
1741 | bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { | |||
1742 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); | |||
1743 | return RequireCompleteExprType(E, Diagnoser); | |||
1744 | } | |||
1745 | ||||
1746 | bool RequireLiteralType(SourceLocation Loc, QualType T, | |||
1747 | TypeDiagnoser &Diagnoser); | |||
1748 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); | |||
1749 | ||||
1750 | template <typename... Ts> | |||
1751 | bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, | |||
1752 | const Ts &...Args) { | |||
1753 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); | |||
1754 | return RequireLiteralType(Loc, T, Diagnoser); | |||
1755 | } | |||
1756 | ||||
1757 | QualType getElaboratedType(ElaboratedTypeKeyword Keyword, | |||
1758 | const CXXScopeSpec &SS, QualType T, | |||
1759 | TagDecl *OwnedTagDecl = nullptr); | |||
1760 | ||||
1761 | QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); | |||
1762 | /// If AsUnevaluated is false, E is treated as though it were an evaluated | |||
1763 | /// context, such as when building a type for decltype(auto). | |||
1764 | QualType BuildDecltypeType(Expr *E, SourceLocation Loc, | |||
1765 | bool AsUnevaluated = true); | |||
1766 | QualType BuildUnaryTransformType(QualType BaseType, | |||
1767 | UnaryTransformType::UTTKind UKind, | |||
1768 | SourceLocation Loc); | |||
1769 | ||||
1770 | //===--------------------------------------------------------------------===// | |||
1771 | // Symbol table / Decl tracking callbacks: SemaDecl.cpp. | |||
1772 | // | |||
1773 | ||||
1774 | struct SkipBodyInfo { | |||
1775 | SkipBodyInfo() | |||
1776 | : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), | |||
1777 | New(nullptr) {} | |||
1778 | bool ShouldSkip; | |||
1779 | bool CheckSameAsPrevious; | |||
1780 | NamedDecl *Previous; | |||
1781 | NamedDecl *New; | |||
1782 | }; | |||
1783 | ||||
1784 | DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); | |||
1785 | ||||
1786 | void DiagnoseUseOfUnimplementedSelectors(); | |||
1787 | ||||
1788 | bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; | |||
1789 | ||||
1790 | ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | |||
1791 | Scope *S, CXXScopeSpec *SS = nullptr, | |||
1792 | bool isClassName = false, bool HasTrailingDot = false, | |||
1793 | ParsedType ObjectType = nullptr, | |||
1794 | bool IsCtorOrDtorName = false, | |||
1795 | bool WantNontrivialTypeSourceInfo = false, | |||
1796 | bool IsClassTemplateDeductionContext = true, | |||
1797 | IdentifierInfo **CorrectedII = nullptr); | |||
1798 | TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); | |||
1799 | bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); | |||
1800 | void DiagnoseUnknownTypeName(IdentifierInfo *&II, | |||
1801 | SourceLocation IILoc, | |||
1802 | Scope *S, | |||
1803 | CXXScopeSpec *SS, | |||
1804 | ParsedType &SuggestedType, | |||
1805 | bool IsTemplateName = false); | |||
1806 | ||||
1807 | /// Attempt to behave like MSVC in situations where lookup of an unqualified | |||
1808 | /// type name has failed in a dependent context. In these situations, we | |||
1809 | /// automatically form a DependentTypeName that will retry lookup in a related | |||
1810 | /// scope during instantiation. | |||
1811 | ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | |||
1812 | SourceLocation NameLoc, | |||
1813 | bool IsTemplateTypeArg); | |||
1814 | ||||
1815 | /// Describes the result of the name lookup and resolution performed | |||
1816 | /// by \c ClassifyName(). | |||
1817 | enum NameClassificationKind { | |||
1818 | NC_Unknown, | |||
1819 | NC_Error, | |||
1820 | NC_Keyword, | |||
1821 | NC_Type, | |||
1822 | NC_Expression, | |||
1823 | NC_NestedNameSpecifier, | |||
1824 | NC_TypeTemplate, | |||
1825 | NC_VarTemplate, | |||
1826 | NC_FunctionTemplate, | |||
1827 | NC_UndeclaredTemplate, | |||
1828 | }; | |||
1829 | ||||
1830 | class NameClassification { | |||
1831 | NameClassificationKind Kind; | |||
1832 | ExprResult Expr; | |||
1833 | TemplateName Template; | |||
1834 | ParsedType Type; | |||
1835 | ||||
1836 | explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} | |||
1837 | ||||
1838 | public: | |||
1839 | NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} | |||
1840 | ||||
1841 | NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} | |||
1842 | ||||
1843 | NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} | |||
1844 | ||||
1845 | static NameClassification Error() { | |||
1846 | return NameClassification(NC_Error); | |||
1847 | } | |||
1848 | ||||
1849 | static NameClassification Unknown() { | |||
1850 | return NameClassification(NC_Unknown); | |||
1851 | } | |||
1852 | ||||
1853 | static NameClassification NestedNameSpecifier() { | |||
1854 | return NameClassification(NC_NestedNameSpecifier); | |||
1855 | } | |||
1856 | ||||
1857 | static NameClassification TypeTemplate(TemplateName Name) { | |||
1858 | NameClassification Result(NC_TypeTemplate); | |||
1859 | Result.Template = Name; | |||
1860 | return Result; | |||
1861 | } | |||
1862 | ||||
1863 | static NameClassification VarTemplate(TemplateName Name) { | |||
1864 | NameClassification Result(NC_VarTemplate); | |||
1865 | Result.Template = Name; | |||
1866 | return Result; | |||
1867 | } | |||
1868 | ||||
1869 | static NameClassification FunctionTemplate(TemplateName Name) { | |||
1870 | NameClassification Result(NC_FunctionTemplate); | |||
1871 | Result.Template = Name; | |||
1872 | return Result; | |||
1873 | } | |||
1874 | ||||
1875 | static NameClassification UndeclaredTemplate(TemplateName Name) { | |||
1876 | NameClassification Result(NC_UndeclaredTemplate); | |||
1877 | Result.Template = Name; | |||
1878 | return Result; | |||
1879 | } | |||
1880 | ||||
1881 | NameClassificationKind getKind() const { return Kind; } | |||
1882 | ||||
1883 | ParsedType getType() const { | |||
1884 | assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail ("Kind == NC_Type", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 1884, __PRETTY_FUNCTION__)); | |||
1885 | return Type; | |||
1886 | } | |||
1887 | ||||
1888 | ExprResult getExpression() const { | |||
1889 | assert(Kind == NC_Expression)((Kind == NC_Expression) ? static_cast<void> (0) : __assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 1889, __PRETTY_FUNCTION__)); | |||
1890 | return Expr; | |||
1891 | } | |||
1892 | ||||
1893 | TemplateName getTemplateName() const { | |||
1894 | assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast <void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 1895, __PRETTY_FUNCTION__)) | |||
1895 | Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast <void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 1895, __PRETTY_FUNCTION__)); | |||
1896 | return Template; | |||
1897 | } | |||
1898 | ||||
1899 | TemplateNameKind getTemplateNameKind() const { | |||
1900 | switch (Kind) { | |||
1901 | case NC_TypeTemplate: | |||
1902 | return TNK_Type_template; | |||
1903 | case NC_FunctionTemplate: | |||
1904 | return TNK_Function_template; | |||
1905 | case NC_VarTemplate: | |||
1906 | return TNK_Var_template; | |||
1907 | case NC_UndeclaredTemplate: | |||
1908 | return TNK_Undeclared_template; | |||
1909 | default: | |||
1910 | llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification." , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 1910); | |||
1911 | } | |||
1912 | } | |||
1913 | }; | |||
1914 | ||||
1915 | /// Perform name lookup on the given name, classifying it based on | |||
1916 | /// the results of name lookup and the following token. | |||
1917 | /// | |||
1918 | /// This routine is used by the parser to resolve identifiers and help direct | |||
1919 | /// parsing. When the identifier cannot be found, this routine will attempt | |||
1920 | /// to correct the typo and classify based on the resulting name. | |||
1921 | /// | |||
1922 | /// \param S The scope in which we're performing name lookup. | |||
1923 | /// | |||
1924 | /// \param SS The nested-name-specifier that precedes the name. | |||
1925 | /// | |||
1926 | /// \param Name The identifier. If typo correction finds an alternative name, | |||
1927 | /// this pointer parameter will be updated accordingly. | |||
1928 | /// | |||
1929 | /// \param NameLoc The location of the identifier. | |||
1930 | /// | |||
1931 | /// \param NextToken The token following the identifier. Used to help | |||
1932 | /// disambiguate the name. | |||
1933 | /// | |||
1934 | /// \param IsAddressOfOperand True if this name is the operand of a unary | |||
1935 | /// address of ('&') expression, assuming it is classified as an | |||
1936 | /// expression. | |||
1937 | /// | |||
1938 | /// \param CCC The correction callback, if typo correction is desired. | |||
1939 | NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, | |||
1940 | IdentifierInfo *&Name, SourceLocation NameLoc, | |||
1941 | const Token &NextToken, | |||
1942 | bool IsAddressOfOperand, | |||
1943 | CorrectionCandidateCallback *CCC = nullptr); | |||
1944 | ||||
1945 | /// Describes the detailed kind of a template name. Used in diagnostics. | |||
1946 | enum class TemplateNameKindForDiagnostics { | |||
1947 | ClassTemplate, | |||
1948 | FunctionTemplate, | |||
1949 | VarTemplate, | |||
1950 | AliasTemplate, | |||
1951 | TemplateTemplateParam, | |||
1952 | DependentTemplate | |||
1953 | }; | |||
1954 | TemplateNameKindForDiagnostics | |||
1955 | getTemplateNameKindForDiagnostics(TemplateName Name); | |||
1956 | ||||
1957 | /// Determine whether it's plausible that E was intended to be a | |||
1958 | /// template-name. | |||
1959 | bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { | |||
1960 | if (!getLangOpts().CPlusPlus || E.isInvalid()) | |||
1961 | return false; | |||
1962 | Dependent = false; | |||
1963 | if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) | |||
1964 | return !DRE->hasExplicitTemplateArgs(); | |||
1965 | if (auto *ME = dyn_cast<MemberExpr>(E.get())) | |||
1966 | return !ME->hasExplicitTemplateArgs(); | |||
1967 | Dependent = true; | |||
1968 | if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) | |||
1969 | return !DSDRE->hasExplicitTemplateArgs(); | |||
1970 | if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) | |||
1971 | return !DSME->hasExplicitTemplateArgs(); | |||
1972 | // Any additional cases recognized here should also be handled by | |||
1973 | // diagnoseExprIntendedAsTemplateName. | |||
1974 | return false; | |||
1975 | } | |||
1976 | void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, | |||
1977 | SourceLocation Less, | |||
1978 | SourceLocation Greater); | |||
1979 | ||||
1980 | Decl *ActOnDeclarator(Scope *S, Declarator &D); | |||
1981 | ||||
1982 | NamedDecl *HandleDeclarator(Scope *S, Declarator &D, | |||
1983 | MultiTemplateParamsArg TemplateParameterLists); | |||
1984 | void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); | |||
1985 | bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); | |||
1986 | bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | |||
1987 | DeclarationName Name, SourceLocation Loc, | |||
1988 | bool IsTemplateId); | |||
1989 | void | |||
1990 | diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, | |||
1991 | SourceLocation FallbackLoc, | |||
1992 | SourceLocation ConstQualLoc = SourceLocation(), | |||
1993 | SourceLocation VolatileQualLoc = SourceLocation(), | |||
1994 | SourceLocation RestrictQualLoc = SourceLocation(), | |||
1995 | SourceLocation AtomicQualLoc = SourceLocation(), | |||
1996 | SourceLocation UnalignedQualLoc = SourceLocation()); | |||
1997 | ||||
1998 | static bool adjustContextForLocalExternDecl(DeclContext *&DC); | |||
1999 | void DiagnoseFunctionSpecifiers(const DeclSpec &DS); | |||
2000 | NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, | |||
2001 | const LookupResult &R); | |||
2002 | NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); | |||
2003 | void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | |||
2004 | const LookupResult &R); | |||
2005 | void CheckShadow(Scope *S, VarDecl *D); | |||
2006 | ||||
2007 | /// Warn if 'E', which is an expression that is about to be modified, refers | |||
2008 | /// to a shadowing declaration. | |||
2009 | void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); | |||
2010 | ||||
2011 | void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); | |||
2012 | ||||
2013 | private: | |||
2014 | /// Map of current shadowing declarations to shadowed declarations. Warn if | |||
2015 | /// it looks like the user is trying to modify the shadowing declaration. | |||
2016 | llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; | |||
2017 | ||||
2018 | public: | |||
2019 | void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); | |||
2020 | void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); | |||
2021 | void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | |||
2022 | TypedefNameDecl *NewTD); | |||
2023 | void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); | |||
2024 | NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | |||
2025 | TypeSourceInfo *TInfo, | |||
2026 | LookupResult &Previous); | |||
2027 | NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, | |||
2028 | LookupResult &Previous, bool &Redeclaration); | |||
2029 | NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, | |||
2030 | TypeSourceInfo *TInfo, | |||
2031 | LookupResult &Previous, | |||
2032 | MultiTemplateParamsArg TemplateParamLists, | |||
2033 | bool &AddToScope, | |||
2034 | ArrayRef<BindingDecl *> Bindings = None); | |||
2035 | NamedDecl * | |||
2036 | ActOnDecompositionDeclarator(Scope *S, Declarator &D, | |||
2037 | MultiTemplateParamsArg TemplateParamLists); | |||
2038 | // Returns true if the variable declaration is a redeclaration | |||
2039 | bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); | |||
2040 | void CheckVariableDeclarationType(VarDecl *NewVD); | |||
2041 | bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | |||
2042 | Expr *Init); | |||
2043 | void CheckCompleteVariableDeclaration(VarDecl *VD); | |||
2044 | void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); | |||
2045 | void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); | |||
2046 | ||||
2047 | NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, | |||
2048 | TypeSourceInfo *TInfo, | |||
2049 | LookupResult &Previous, | |||
2050 | MultiTemplateParamsArg TemplateParamLists, | |||
2051 | bool &AddToScope); | |||
2052 | bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); | |||
2053 | ||||
2054 | bool CheckConstexprFunctionDecl(const FunctionDecl *FD); | |||
2055 | bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); | |||
2056 | ||||
2057 | void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); | |||
2058 | void FindHiddenVirtualMethods(CXXMethodDecl *MD, | |||
2059 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); | |||
2060 | void NoteHiddenVirtualMethods(CXXMethodDecl *MD, | |||
2061 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); | |||
2062 | // Returns true if the function declaration is a redeclaration | |||
2063 | bool CheckFunctionDeclaration(Scope *S, | |||
2064 | FunctionDecl *NewFD, LookupResult &Previous, | |||
2065 | bool IsMemberSpecialization); | |||
2066 | bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); | |||
2067 | bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, | |||
2068 | QualType NewT, QualType OldT); | |||
2069 | void CheckMain(FunctionDecl *FD, const DeclSpec &D); | |||
2070 | void CheckMSVCRTEntryPoint(FunctionDecl *FD); | |||
2071 | Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); | |||
2072 | Decl *ActOnParamDeclarator(Scope *S, Declarator &D); | |||
2073 | ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, | |||
2074 | SourceLocation Loc, | |||
2075 | QualType T); | |||
2076 | ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, | |||
2077 | SourceLocation NameLoc, IdentifierInfo *Name, | |||
2078 | QualType T, TypeSourceInfo *TSInfo, | |||
2079 | StorageClass SC); | |||
2080 | void ActOnParamDefaultArgument(Decl *param, | |||
2081 | SourceLocation EqualLoc, | |||
2082 | Expr *defarg); | |||
2083 | void ActOnParamUnparsedDefaultArgument(Decl *param, | |||
2084 | SourceLocation EqualLoc, | |||
2085 | SourceLocation ArgLoc); | |||
2086 | void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); | |||
2087 | bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, | |||
2088 | SourceLocation EqualLoc); | |||
2089 | ||||
2090 | void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); | |||
2091 | void ActOnUninitializedDecl(Decl *dcl); | |||
2092 | void ActOnInitializerError(Decl *Dcl); | |||
2093 | ||||
2094 | void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); | |||
2095 | void ActOnCXXForRangeDecl(Decl *D); | |||
2096 | StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | |||
2097 | IdentifierInfo *Ident, | |||
2098 | ParsedAttributes &Attrs, | |||
2099 | SourceLocation AttrEnd); | |||
2100 | void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); | |||
2101 | void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); | |||
2102 | void CheckStaticLocalForDllExport(VarDecl *VD); | |||
2103 | void FinalizeDeclaration(Decl *D); | |||
2104 | DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | |||
2105 | ArrayRef<Decl *> Group); | |||
2106 | DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); | |||
2107 | ||||
2108 | /// Should be called on all declarations that might have attached | |||
2109 | /// documentation comments. | |||
2110 | void ActOnDocumentableDecl(Decl *D); | |||
2111 | void ActOnDocumentableDecls(ArrayRef<Decl *> Group); | |||
2112 | ||||
2113 | void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | |||
2114 | SourceLocation LocAfterDecls); | |||
2115 | void CheckForFunctionRedefinition( | |||
2116 | FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, | |||
2117 | SkipBodyInfo *SkipBody = nullptr); | |||
2118 | Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, | |||
2119 | MultiTemplateParamsArg TemplateParamLists, | |||
2120 | SkipBodyInfo *SkipBody = nullptr); | |||
2121 | Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, | |||
2122 | SkipBodyInfo *SkipBody = nullptr); | |||
2123 | void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); | |||
2124 | bool isObjCMethodDecl(Decl *D) { | |||
2125 | return D && isa<ObjCMethodDecl>(D); | |||
2126 | } | |||
2127 | ||||
2128 | /// Determine whether we can delay parsing the body of a function or | |||
2129 | /// function template until it is used, assuming we don't care about emitting | |||
2130 | /// code for that function. | |||
2131 | /// | |||
2132 | /// This will be \c false if we may need the body of the function in the | |||
2133 | /// middle of parsing an expression (where it's impractical to switch to | |||
2134 | /// parsing a different function), for instance, if it's constexpr in C++11 | |||
2135 | /// or has an 'auto' return type in C++14. These cases are essentially bugs. | |||
2136 | bool canDelayFunctionBody(const Declarator &D); | |||
2137 | ||||
2138 | /// Determine whether we can skip parsing the body of a function | |||
2139 | /// definition, assuming we don't care about analyzing its body or emitting | |||
2140 | /// code for that function. | |||
2141 | /// | |||
2142 | /// This will be \c false only if we may need the body of the function in | |||
2143 | /// order to parse the rest of the program (for instance, if it is | |||
2144 | /// \c constexpr in C++11 or has an 'auto' return type in C++14). | |||
2145 | bool canSkipFunctionBody(Decl *D); | |||
2146 | ||||
2147 | void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); | |||
2148 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); | |||
2149 | Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); | |||
2150 | Decl *ActOnSkippedFunctionBody(Decl *Decl); | |||
2151 | void ActOnFinishInlineFunctionDef(FunctionDecl *D); | |||
2152 | ||||
2153 | /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an | |||
2154 | /// attribute for which parsing is delayed. | |||
2155 | void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); | |||
2156 | ||||
2157 | /// Diagnose any unused parameters in the given sequence of | |||
2158 | /// ParmVarDecl pointers. | |||
2159 | void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); | |||
2160 | ||||
2161 | /// Diagnose whether the size of parameters or return value of a | |||
2162 | /// function or obj-c method definition is pass-by-value and larger than a | |||
2163 | /// specified threshold. | |||
2164 | void | |||
2165 | DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, | |||
2166 | QualType ReturnTy, NamedDecl *D); | |||
2167 | ||||
2168 | void DiagnoseInvalidJumps(Stmt *Body); | |||
2169 | Decl *ActOnFileScopeAsmDecl(Expr *expr, | |||
2170 | SourceLocation AsmLoc, | |||
2171 | SourceLocation RParenLoc); | |||
2172 | ||||
2173 | /// Handle a C++11 empty-declaration and attribute-declaration. | |||
2174 | Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, | |||
2175 | SourceLocation SemiLoc); | |||
2176 | ||||
2177 | enum class ModuleDeclKind { | |||
2178 | Interface, ///< 'export module X;' | |||
2179 | Implementation, ///< 'module X;' | |||
2180 | }; | |||
2181 | ||||
2182 | /// The parser has processed a module-declaration that begins the definition | |||
2183 | /// of a module interface or implementation. | |||
2184 | DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, | |||
2185 | SourceLocation ModuleLoc, ModuleDeclKind MDK, | |||
2186 | ModuleIdPath Path, bool IsFirstDecl); | |||
2187 | ||||
2188 | /// The parser has processed a global-module-fragment declaration that begins | |||
2189 | /// the definition of the global module fragment of the current module unit. | |||
2190 | /// \param ModuleLoc The location of the 'module' keyword. | |||
2191 | DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); | |||
2192 | ||||
2193 | /// The parser has processed a private-module-fragment declaration that begins | |||
2194 | /// the definition of the private module fragment of the current module unit. | |||
2195 | /// \param ModuleLoc The location of the 'module' keyword. | |||
2196 | /// \param PrivateLoc The location of the 'private' keyword. | |||
2197 | DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, | |||
2198 | SourceLocation PrivateLoc); | |||
2199 | ||||
2200 | /// The parser has processed a module import declaration. | |||
2201 | /// | |||
2202 | /// \param StartLoc The location of the first token in the declaration. This | |||
2203 | /// could be the location of an '@', 'export', or 'import'. | |||
2204 | /// \param ExportLoc The location of the 'export' keyword, if any. | |||
2205 | /// \param ImportLoc The location of the 'import' keyword. | |||
2206 | /// \param Path The module access path. | |||
2207 | DeclResult ActOnModuleImport(SourceLocation StartLoc, | |||
2208 | SourceLocation ExportLoc, | |||
2209 | SourceLocation ImportLoc, ModuleIdPath Path); | |||
2210 | DeclResult ActOnModuleImport(SourceLocation StartLoc, | |||
2211 | SourceLocation ExportLoc, | |||
2212 | SourceLocation ImportLoc, Module *M, | |||
2213 | ModuleIdPath Path = {}); | |||
2214 | ||||
2215 | /// The parser has processed a module import translated from a | |||
2216 | /// #include or similar preprocessing directive. | |||
2217 | void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); | |||
2218 | void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); | |||
2219 | ||||
2220 | /// The parsed has entered a submodule. | |||
2221 | void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); | |||
2222 | /// The parser has left a submodule. | |||
2223 | void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); | |||
2224 | ||||
2225 | /// Create an implicit import of the given module at the given | |||
2226 | /// source location, for error recovery, if possible. | |||
2227 | /// | |||
2228 | /// This routine is typically used when an entity found by name lookup | |||
2229 | /// is actually hidden within a module that we know about but the user | |||
2230 | /// has forgotten to import. | |||
2231 | void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, | |||
2232 | Module *Mod); | |||
2233 | ||||
2234 | /// Kinds of missing import. Note, the values of these enumerators correspond | |||
2235 | /// to %select values in diagnostics. | |||
2236 | enum class MissingImportKind { | |||
2237 | Declaration, | |||
2238 | Definition, | |||
2239 | DefaultArgument, | |||
2240 | ExplicitSpecialization, | |||
2241 | PartialSpecialization | |||
2242 | }; | |||
2243 | ||||
2244 | /// Diagnose that the specified declaration needs to be visible but | |||
2245 | /// isn't, and suggest a module import that would resolve the problem. | |||
2246 | void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, | |||
2247 | MissingImportKind MIK, bool Recover = true); | |||
2248 | void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, | |||
2249 | SourceLocation DeclLoc, ArrayRef<Module *> Modules, | |||
2250 | MissingImportKind MIK, bool Recover); | |||
2251 | ||||
2252 | Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, | |||
2253 | SourceLocation LBraceLoc); | |||
2254 | Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, | |||
2255 | SourceLocation RBraceLoc); | |||
2256 | ||||
2257 | /// We've found a use of a templated declaration that would trigger an | |||
2258 | /// implicit instantiation. Check that any relevant explicit specializations | |||
2259 | /// and partial specializations are visible, and diagnose if not. | |||
2260 | void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); | |||
2261 | ||||
2262 | /// We've found a use of a template specialization that would select a | |||
2263 | /// partial specialization. Check that the partial specialization is visible, | |||
2264 | /// and diagnose if not. | |||
2265 | void checkPartialSpecializationVisibility(SourceLocation Loc, | |||
2266 | NamedDecl *Spec); | |||
2267 | ||||
2268 | /// Retrieve a suitable printing policy for diagnostics. | |||
2269 | PrintingPolicy getPrintingPolicy() const { | |||
2270 | return getPrintingPolicy(Context, PP); | |||
2271 | } | |||
2272 | ||||
2273 | /// Retrieve a suitable printing policy for diagnostics. | |||
2274 | static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, | |||
2275 | const Preprocessor &PP); | |||
2276 | ||||
2277 | /// Scope actions. | |||
2278 | void ActOnPopScope(SourceLocation Loc, Scope *S); | |||
2279 | void ActOnTranslationUnitScope(Scope *S); | |||
2280 | ||||
2281 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
2282 | RecordDecl *&AnonRecord); | |||
2283 | Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
2284 | MultiTemplateParamsArg TemplateParams, | |||
2285 | bool IsExplicitInstantiation, | |||
2286 | RecordDecl *&AnonRecord); | |||
2287 | ||||
2288 | Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | |||
2289 | AccessSpecifier AS, | |||
2290 | RecordDecl *Record, | |||
2291 | const PrintingPolicy &Policy); | |||
2292 | ||||
2293 | Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | |||
2294 | RecordDecl *Record); | |||
2295 | ||||
2296 | /// Common ways to introduce type names without a tag for use in diagnostics. | |||
2297 | /// Keep in sync with err_tag_reference_non_tag. | |||
2298 | enum NonTagKind { | |||
2299 | NTK_NonStruct, | |||
2300 | NTK_NonClass, | |||
2301 | NTK_NonUnion, | |||
2302 | NTK_NonEnum, | |||
2303 | NTK_Typedef, | |||
2304 | NTK_TypeAlias, | |||
2305 | NTK_Template, | |||
2306 | NTK_TypeAliasTemplate, | |||
2307 | NTK_TemplateTemplateArgument, | |||
2308 | }; | |||
2309 | ||||
2310 | /// Given a non-tag type declaration, returns an enum useful for indicating | |||
2311 | /// what kind of non-tag type this is. | |||
2312 | NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); | |||
2313 | ||||
2314 | bool isAcceptableTagRedeclaration(const TagDecl *Previous, | |||
2315 | TagTypeKind NewTag, bool isDefinition, | |||
2316 | SourceLocation NewTagLoc, | |||
2317 | const IdentifierInfo *Name); | |||
2318 | ||||
2319 | enum TagUseKind { | |||
2320 | TUK_Reference, // Reference to a tag: 'struct foo *X;' | |||
2321 | TUK_Declaration, // Fwd decl of a tag: 'struct foo;' | |||
2322 | TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' | |||
2323 | TUK_Friend // Friend declaration: 'friend struct foo;' | |||
2324 | }; | |||
2325 | ||||
2326 | Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | |||
2327 | SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, | |||
2328 | SourceLocation NameLoc, const ParsedAttributesView &Attr, | |||
2329 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, | |||
2330 | MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, | |||
2331 | bool &IsDependent, SourceLocation ScopedEnumKWLoc, | |||
2332 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | |||
2333 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | |||
2334 | SkipBodyInfo *SkipBody = nullptr); | |||
2335 | ||||
2336 | Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, | |||
2337 | unsigned TagSpec, SourceLocation TagLoc, | |||
2338 | CXXScopeSpec &SS, IdentifierInfo *Name, | |||
2339 | SourceLocation NameLoc, | |||
2340 | const ParsedAttributesView &Attr, | |||
2341 | MultiTemplateParamsArg TempParamLists); | |||
2342 | ||||
2343 | TypeResult ActOnDependentTag(Scope *S, | |||
2344 | unsigned TagSpec, | |||
2345 | TagUseKind TUK, | |||
2346 | const CXXScopeSpec &SS, | |||
2347 | IdentifierInfo *Name, | |||
2348 | SourceLocation TagLoc, | |||
2349 | SourceLocation NameLoc); | |||
2350 | ||||
2351 | void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, | |||
2352 | IdentifierInfo *ClassName, | |||
2353 | SmallVectorImpl<Decl *> &Decls); | |||
2354 | Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | |||
2355 | Declarator &D, Expr *BitfieldWidth); | |||
2356 | ||||
2357 | FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, | |||
2358 | Declarator &D, Expr *BitfieldWidth, | |||
2359 | InClassInitStyle InitStyle, | |||
2360 | AccessSpecifier AS); | |||
2361 | MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, | |||
2362 | SourceLocation DeclStart, Declarator &D, | |||
2363 | Expr *BitfieldWidth, | |||
2364 | InClassInitStyle InitStyle, | |||
2365 | AccessSpecifier AS, | |||
2366 | const ParsedAttr &MSPropertyAttr); | |||
2367 | ||||
2368 | FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, | |||
2369 | TypeSourceInfo *TInfo, | |||
2370 | RecordDecl *Record, SourceLocation Loc, | |||
2371 | bool Mutable, Expr *BitfieldWidth, | |||
2372 | InClassInitStyle InitStyle, | |||
2373 | SourceLocation TSSL, | |||
2374 | AccessSpecifier AS, NamedDecl *PrevDecl, | |||
2375 | Declarator *D = nullptr); | |||
2376 | ||||
2377 | bool CheckNontrivialField(FieldDecl *FD); | |||
2378 | void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); | |||
2379 | ||||
2380 | enum TrivialABIHandling { | |||
2381 | /// The triviality of a method unaffected by "trivial_abi". | |||
2382 | TAH_IgnoreTrivialABI, | |||
2383 | ||||
2384 | /// The triviality of a method affected by "trivial_abi". | |||
2385 | TAH_ConsiderTrivialABI | |||
2386 | }; | |||
2387 | ||||
2388 | bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
2389 | TrivialABIHandling TAH = TAH_IgnoreTrivialABI, | |||
2390 | bool Diagnose = false); | |||
2391 | CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); | |||
2392 | void ActOnLastBitfield(SourceLocation DeclStart, | |||
2393 | SmallVectorImpl<Decl *> &AllIvarDecls); | |||
2394 | Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, | |||
2395 | Declarator &D, Expr *BitfieldWidth, | |||
2396 | tok::ObjCKeywordKind visibility); | |||
2397 | ||||
2398 | // This is used for both record definitions and ObjC interface declarations. | |||
2399 | void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, | |||
2400 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | |||
2401 | SourceLocation RBrac, const ParsedAttributesView &AttrList); | |||
2402 | ||||
2403 | /// ActOnTagStartDefinition - Invoked when we have entered the | |||
2404 | /// scope of a tag's definition (e.g., for an enumeration, class, | |||
2405 | /// struct, or union). | |||
2406 | void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); | |||
2407 | ||||
2408 | /// Perform ODR-like check for C/ObjC when merging tag types from modules. | |||
2409 | /// Differently from C++, actually parse the body and reject / error out | |||
2410 | /// in case of a structural mismatch. | |||
2411 | bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, | |||
2412 | SkipBodyInfo &SkipBody); | |||
2413 | ||||
2414 | typedef void *SkippedDefinitionContext; | |||
2415 | ||||
2416 | /// Invoked when we enter a tag definition that we're skipping. | |||
2417 | SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); | |||
2418 | ||||
2419 | Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); | |||
2420 | ||||
2421 | /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a | |||
2422 | /// C++ record definition's base-specifiers clause and are starting its | |||
2423 | /// member declarations. | |||
2424 | void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, | |||
2425 | SourceLocation FinalLoc, | |||
2426 | bool IsFinalSpelledSealed, | |||
2427 | SourceLocation LBraceLoc); | |||
2428 | ||||
2429 | /// ActOnTagFinishDefinition - Invoked once we have finished parsing | |||
2430 | /// the definition of a tag (enumeration, class, struct, or union). | |||
2431 | void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, | |||
2432 | SourceRange BraceRange); | |||
2433 | ||||
2434 | void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); | |||
2435 | ||||
2436 | void ActOnObjCContainerFinishDefinition(); | |||
2437 | ||||
2438 | /// Invoked when we must temporarily exit the objective-c container | |||
2439 | /// scope for parsing/looking-up C constructs. | |||
2440 | /// | |||
2441 | /// Must be followed by a call to \see ActOnObjCReenterContainerContext | |||
2442 | void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); | |||
2443 | void ActOnObjCReenterContainerContext(DeclContext *DC); | |||
2444 | ||||
2445 | /// ActOnTagDefinitionError - Invoked when there was an unrecoverable | |||
2446 | /// error parsing the definition of a tag. | |||
2447 | void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); | |||
2448 | ||||
2449 | EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, | |||
2450 | EnumConstantDecl *LastEnumConst, | |||
2451 | SourceLocation IdLoc, | |||
2452 | IdentifierInfo *Id, | |||
2453 | Expr *val); | |||
2454 | bool CheckEnumUnderlyingType(TypeSourceInfo *TI); | |||
2455 | bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | |||
2456 | QualType EnumUnderlyingTy, bool IsFixed, | |||
2457 | const EnumDecl *Prev); | |||
2458 | ||||
2459 | /// Determine whether the body of an anonymous enumeration should be skipped. | |||
2460 | /// \param II The name of the first enumerator. | |||
2461 | SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | |||
2462 | SourceLocation IILoc); | |||
2463 | ||||
2464 | Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, | |||
2465 | SourceLocation IdLoc, IdentifierInfo *Id, | |||
2466 | const ParsedAttributesView &Attrs, | |||
2467 | SourceLocation EqualLoc, Expr *Val); | |||
2468 | void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | |||
2469 | Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, | |||
2470 | const ParsedAttributesView &Attr); | |||
2471 | ||||
2472 | DeclContext *getContainingDC(DeclContext *DC); | |||
2473 | ||||
2474 | /// Set the current declaration context until it gets popped. | |||
2475 | void PushDeclContext(Scope *S, DeclContext *DC); | |||
2476 | void PopDeclContext(); | |||
2477 | ||||
2478 | /// EnterDeclaratorContext - Used when we must lookup names in the context | |||
2479 | /// of a declarator's nested name specifier. | |||
2480 | void EnterDeclaratorContext(Scope *S, DeclContext *DC); | |||
2481 | void ExitDeclaratorContext(Scope *S); | |||
2482 | ||||
2483 | /// Push the parameters of D, which must be a function, into scope. | |||
2484 | void ActOnReenterFunctionContext(Scope* S, Decl* D); | |||
2485 | void ActOnExitFunctionContext(); | |||
2486 | ||||
2487 | DeclContext *getFunctionLevelDeclContext(); | |||
2488 | ||||
2489 | /// getCurFunctionDecl - If inside of a function body, this returns a pointer | |||
2490 | /// to the function decl for the function being parsed. If we're currently | |||
2491 | /// in a 'block', this returns the containing context. | |||
2492 | FunctionDecl *getCurFunctionDecl(); | |||
2493 | ||||
2494 | /// getCurMethodDecl - If inside of a method body, this returns a pointer to | |||
2495 | /// the method decl for the method being parsed. If we're currently | |||
2496 | /// in a 'block', this returns the containing context. | |||
2497 | ObjCMethodDecl *getCurMethodDecl(); | |||
2498 | ||||
2499 | /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method | |||
2500 | /// or C function we're in, otherwise return null. If we're currently | |||
2501 | /// in a 'block', this returns the containing context. | |||
2502 | NamedDecl *getCurFunctionOrMethodDecl(); | |||
2503 | ||||
2504 | /// Add this decl to the scope shadowed decl chains. | |||
2505 | void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); | |||
2506 | ||||
2507 | /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true | |||
2508 | /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns | |||
2509 | /// true if 'D' belongs to the given declaration context. | |||
2510 | /// | |||
2511 | /// \param AllowInlineNamespace If \c true, allow the declaration to be in the | |||
2512 | /// enclosing namespace set of the context, rather than contained | |||
2513 | /// directly within it. | |||
2514 | bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, | |||
2515 | bool AllowInlineNamespace = false); | |||
2516 | ||||
2517 | /// Finds the scope corresponding to the given decl context, if it | |||
2518 | /// happens to be an enclosing scope. Otherwise return NULL. | |||
2519 | static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); | |||
2520 | ||||
2521 | /// Subroutines of ActOnDeclarator(). | |||
2522 | TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | |||
2523 | TypeSourceInfo *TInfo); | |||
2524 | bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); | |||
2525 | ||||
2526 | /// Describes the kind of merge to perform for availability | |||
2527 | /// attributes (including "deprecated", "unavailable", and "availability"). | |||
2528 | enum AvailabilityMergeKind { | |||
2529 | /// Don't merge availability attributes at all. | |||
2530 | AMK_None, | |||
2531 | /// Merge availability attributes for a redeclaration, which requires | |||
2532 | /// an exact match. | |||
2533 | AMK_Redeclaration, | |||
2534 | /// Merge availability attributes for an override, which requires | |||
2535 | /// an exact match or a weakening of constraints. | |||
2536 | AMK_Override, | |||
2537 | /// Merge availability attributes for an implementation of | |||
2538 | /// a protocol requirement. | |||
2539 | AMK_ProtocolImplementation, | |||
2540 | }; | |||
2541 | ||||
2542 | /// Describes the kind of priority given to an availability attribute. | |||
2543 | /// | |||
2544 | /// The sum of priorities deteremines the final priority of the attribute. | |||
2545 | /// The final priority determines how the attribute will be merged. | |||
2546 | /// An attribute with a lower priority will always remove higher priority | |||
2547 | /// attributes for the specified platform when it is being applied. An | |||
2548 | /// attribute with a higher priority will not be applied if the declaration | |||
2549 | /// already has an availability attribute with a lower priority for the | |||
2550 | /// specified platform. The final prirority values are not expected to match | |||
2551 | /// the values in this enumeration, but instead should be treated as a plain | |||
2552 | /// integer value. This enumeration just names the priority weights that are | |||
2553 | /// used to calculate that final vaue. | |||
2554 | enum AvailabilityPriority : int { | |||
2555 | /// The availability attribute was specified explicitly next to the | |||
2556 | /// declaration. | |||
2557 | AP_Explicit = 0, | |||
2558 | ||||
2559 | /// The availability attribute was applied using '#pragma clang attribute'. | |||
2560 | AP_PragmaClangAttribute = 1, | |||
2561 | ||||
2562 | /// The availability attribute for a specific platform was inferred from | |||
2563 | /// an availability attribute for another platform. | |||
2564 | AP_InferredFromOtherPlatform = 2 | |||
2565 | }; | |||
2566 | ||||
2567 | /// Attribute merging methods. Return true if a new attribute was added. | |||
2568 | AvailabilityAttr *mergeAvailabilityAttr( | |||
2569 | NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, | |||
2570 | VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, | |||
2571 | bool IsUnavailable, StringRef Message, bool IsStrict, | |||
2572 | StringRef Replacement, AvailabilityMergeKind AMK, int Priority, | |||
2573 | unsigned AttrSpellingListIndex); | |||
2574 | TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, | |||
2575 | TypeVisibilityAttr::VisibilityType Vis, | |||
2576 | unsigned AttrSpellingListIndex); | |||
2577 | VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, | |||
2578 | VisibilityAttr::VisibilityType Vis, | |||
2579 | unsigned AttrSpellingListIndex); | |||
2580 | UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range, | |||
2581 | unsigned AttrSpellingListIndex, StringRef Uuid); | |||
2582 | DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, | |||
2583 | unsigned AttrSpellingListIndex); | |||
2584 | DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, | |||
2585 | unsigned AttrSpellingListIndex); | |||
2586 | MSInheritanceAttr * | |||
2587 | mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, | |||
2588 | unsigned AttrSpellingListIndex, | |||
2589 | MSInheritanceAttr::Spelling SemanticSpelling); | |||
2590 | FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, | |||
2591 | IdentifierInfo *Format, int FormatIdx, | |||
2592 | int FirstArg, unsigned AttrSpellingListIndex); | |||
2593 | SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, | |||
2594 | unsigned AttrSpellingListIndex); | |||
2595 | CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name, | |||
2596 | unsigned AttrSpellingListIndex); | |||
2597 | AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range, | |||
2598 | IdentifierInfo *Ident, | |||
2599 | unsigned AttrSpellingListIndex); | |||
2600 | MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range, | |||
2601 | unsigned AttrSpellingListIndex); | |||
2602 | NoSpeculativeLoadHardeningAttr * | |||
2603 | mergeNoSpeculativeLoadHardeningAttr(Decl *D, | |||
2604 | const NoSpeculativeLoadHardeningAttr &AL); | |||
2605 | SpeculativeLoadHardeningAttr * | |||
2606 | mergeSpeculativeLoadHardeningAttr(Decl *D, | |||
2607 | const SpeculativeLoadHardeningAttr &AL); | |||
2608 | OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range, | |||
2609 | unsigned AttrSpellingListIndex); | |||
2610 | InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); | |||
2611 | InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, | |||
2612 | const InternalLinkageAttr &AL); | |||
2613 | CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); | |||
2614 | CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); | |||
2615 | ||||
2616 | void mergeDeclAttributes(NamedDecl *New, Decl *Old, | |||
2617 | AvailabilityMergeKind AMK = AMK_Redeclaration); | |||
2618 | void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | |||
2619 | LookupResult &OldDecls); | |||
2620 | bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, | |||
2621 | bool MergeTypeWithOld); | |||
2622 | bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | |||
2623 | Scope *S, bool MergeTypeWithOld); | |||
2624 | void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); | |||
2625 | void MergeVarDecl(VarDecl *New, LookupResult &Previous); | |||
2626 | void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); | |||
2627 | void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); | |||
2628 | bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); | |||
2629 | void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); | |||
2630 | bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); | |||
2631 | ||||
2632 | // AssignmentAction - This is used by all the assignment diagnostic functions | |||
2633 | // to represent what is actually causing the operation | |||
2634 | enum AssignmentAction { | |||
2635 | AA_Assigning, | |||
2636 | AA_Passing, | |||
2637 | AA_Returning, | |||
2638 | AA_Converting, | |||
2639 | AA_Initializing, | |||
2640 | AA_Sending, | |||
2641 | AA_Casting, | |||
2642 | AA_Passing_CFAudited | |||
2643 | }; | |||
2644 | ||||
2645 | /// C++ Overloading. | |||
2646 | enum OverloadKind { | |||
2647 | /// This is a legitimate overload: the existing declarations are | |||
2648 | /// functions or function templates with different signatures. | |||
2649 | Ovl_Overload, | |||
2650 | ||||
2651 | /// This is not an overload because the signature exactly matches | |||
2652 | /// an existing declaration. | |||
2653 | Ovl_Match, | |||
2654 | ||||
2655 | /// This is not an overload because the lookup results contain a | |||
2656 | /// non-function. | |||
2657 | Ovl_NonFunction | |||
2658 | }; | |||
2659 | OverloadKind CheckOverload(Scope *S, | |||
2660 | FunctionDecl *New, | |||
2661 | const LookupResult &OldDecls, | |||
2662 | NamedDecl *&OldDecl, | |||
2663 | bool IsForUsingDecl); | |||
2664 | bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, | |||
2665 | bool ConsiderCudaAttrs = true); | |||
2666 | ||||
2667 | ImplicitConversionSequence | |||
2668 | TryImplicitConversion(Expr *From, QualType ToType, | |||
2669 | bool SuppressUserConversions, | |||
2670 | bool AllowExplicit, | |||
2671 | bool InOverloadResolution, | |||
2672 | bool CStyle, | |||
2673 | bool AllowObjCWritebackConversion); | |||
2674 | ||||
2675 | bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); | |||
2676 | bool IsFloatingPointPromotion(QualType FromType, QualType ToType); | |||
2677 | bool IsComplexPromotion(QualType FromType, QualType ToType); | |||
2678 | bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, | |||
2679 | bool InOverloadResolution, | |||
2680 | QualType& ConvertedType, bool &IncompatibleObjC); | |||
2681 | bool isObjCPointerConversion(QualType FromType, QualType ToType, | |||
2682 | QualType& ConvertedType, bool &IncompatibleObjC); | |||
2683 | bool isObjCWritebackConversion(QualType FromType, QualType ToType, | |||
2684 | QualType &ConvertedType); | |||
2685 | bool IsBlockPointerConversion(QualType FromType, QualType ToType, | |||
2686 | QualType& ConvertedType); | |||
2687 | bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, | |||
2688 | const FunctionProtoType *NewType, | |||
2689 | unsigned *ArgPos = nullptr); | |||
2690 | void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, | |||
2691 | QualType FromType, QualType ToType); | |||
2692 | ||||
2693 | void maybeExtendBlockObject(ExprResult &E); | |||
2694 | CastKind PrepareCastToObjCObjectPointer(ExprResult &E); | |||
2695 | bool CheckPointerConversion(Expr *From, QualType ToType, | |||
2696 | CastKind &Kind, | |||
2697 | CXXCastPath& BasePath, | |||
2698 | bool IgnoreBaseAccess, | |||
2699 | bool Diagnose = true); | |||
2700 | bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, | |||
2701 | bool InOverloadResolution, | |||
2702 | QualType &ConvertedType); | |||
2703 | bool CheckMemberPointerConversion(Expr *From, QualType ToType, | |||
2704 | CastKind &Kind, | |||
2705 | CXXCastPath &BasePath, | |||
2706 | bool IgnoreBaseAccess); | |||
2707 | bool IsQualificationConversion(QualType FromType, QualType ToType, | |||
2708 | bool CStyle, bool &ObjCLifetimeConversion); | |||
2709 | bool IsFunctionConversion(QualType FromType, QualType ToType, | |||
2710 | QualType &ResultTy); | |||
2711 | bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); | |||
2712 | bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); | |||
2713 | ||||
2714 | ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, | |||
2715 | const VarDecl *NRVOCandidate, | |||
2716 | QualType ResultType, | |||
2717 | Expr *Value, | |||
2718 | bool AllowNRVO = true); | |||
2719 | ||||
2720 | bool CanPerformCopyInitialization(const InitializedEntity &Entity, | |||
2721 | ExprResult Init); | |||
2722 | ExprResult PerformCopyInitialization(const InitializedEntity &Entity, | |||
2723 | SourceLocation EqualLoc, | |||
2724 | ExprResult Init, | |||
2725 | bool TopLevelOfInitList = false, | |||
2726 | bool AllowExplicit = false); | |||
2727 | ExprResult PerformObjectArgumentInitialization(Expr *From, | |||
2728 | NestedNameSpecifier *Qualifier, | |||
2729 | NamedDecl *FoundDecl, | |||
2730 | CXXMethodDecl *Method); | |||
2731 | ||||
2732 | /// Check that the lifetime of the initializer (and its subobjects) is | |||
2733 | /// sufficient for initializing the entity, and perform lifetime extension | |||
2734 | /// (when permitted) if not. | |||
2735 | void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); | |||
2736 | ||||
2737 | ExprResult PerformContextuallyConvertToBool(Expr *From); | |||
2738 | ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); | |||
2739 | ||||
2740 | /// Contexts in which a converted constant expression is required. | |||
2741 | enum CCEKind { | |||
2742 | CCEK_CaseValue, ///< Expression in a case label. | |||
2743 | CCEK_Enumerator, ///< Enumerator value with fixed underlying type. | |||
2744 | CCEK_TemplateArg, ///< Value of a non-type template parameter. | |||
2745 | CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. | |||
2746 | CCEK_ConstexprIf, ///< Condition in a constexpr if statement. | |||
2747 | CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. | |||
2748 | }; | |||
2749 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, | |||
2750 | llvm::APSInt &Value, CCEKind CCE); | |||
2751 | ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, | |||
2752 | APValue &Value, CCEKind CCE); | |||
2753 | ||||
2754 | /// Abstract base class used to perform a contextual implicit | |||
2755 | /// conversion from an expression to any type passing a filter. | |||
2756 | class ContextualImplicitConverter { | |||
2757 | public: | |||
2758 | bool Suppress; | |||
2759 | bool SuppressConversion; | |||
2760 | ||||
2761 | ContextualImplicitConverter(bool Suppress = false, | |||
2762 | bool SuppressConversion = false) | |||
2763 | : Suppress(Suppress), SuppressConversion(SuppressConversion) {} | |||
2764 | ||||
2765 | /// Determine whether the specified type is a valid destination type | |||
2766 | /// for this conversion. | |||
2767 | virtual bool match(QualType T) = 0; | |||
2768 | ||||
2769 | /// Emits a diagnostic complaining that the expression does not have | |||
2770 | /// integral or enumeration type. | |||
2771 | virtual SemaDiagnosticBuilder | |||
2772 | diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; | |||
2773 | ||||
2774 | /// Emits a diagnostic when the expression has incomplete class type. | |||
2775 | virtual SemaDiagnosticBuilder | |||
2776 | diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; | |||
2777 | ||||
2778 | /// Emits a diagnostic when the only matching conversion function | |||
2779 | /// is explicit. | |||
2780 | virtual SemaDiagnosticBuilder diagnoseExplicitConv( | |||
2781 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; | |||
2782 | ||||
2783 | /// Emits a note for the explicit conversion function. | |||
2784 | virtual SemaDiagnosticBuilder | |||
2785 | noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; | |||
2786 | ||||
2787 | /// Emits a diagnostic when there are multiple possible conversion | |||
2788 | /// functions. | |||
2789 | virtual SemaDiagnosticBuilder | |||
2790 | diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; | |||
2791 | ||||
2792 | /// Emits a note for one of the candidate conversions. | |||
2793 | virtual SemaDiagnosticBuilder | |||
2794 | noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; | |||
2795 | ||||
2796 | /// Emits a diagnostic when we picked a conversion function | |||
2797 | /// (for cases when we are not allowed to pick a conversion function). | |||
2798 | virtual SemaDiagnosticBuilder diagnoseConversion( | |||
2799 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; | |||
2800 | ||||
2801 | virtual ~ContextualImplicitConverter() {} | |||
2802 | }; | |||
2803 | ||||
2804 | class ICEConvertDiagnoser : public ContextualImplicitConverter { | |||
2805 | bool AllowScopedEnumerations; | |||
2806 | ||||
2807 | public: | |||
2808 | ICEConvertDiagnoser(bool AllowScopedEnumerations, | |||
2809 | bool Suppress, bool SuppressConversion) | |||
2810 | : ContextualImplicitConverter(Suppress, SuppressConversion), | |||
2811 | AllowScopedEnumerations(AllowScopedEnumerations) {} | |||
2812 | ||||
2813 | /// Match an integral or (possibly scoped) enumeration type. | |||
2814 | bool match(QualType T) override; | |||
2815 | ||||
2816 | SemaDiagnosticBuilder | |||
2817 | diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { | |||
2818 | return diagnoseNotInt(S, Loc, T); | |||
2819 | } | |||
2820 | ||||
2821 | /// Emits a diagnostic complaining that the expression does not have | |||
2822 | /// integral or enumeration type. | |||
2823 | virtual SemaDiagnosticBuilder | |||
2824 | diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; | |||
2825 | }; | |||
2826 | ||||
2827 | /// Perform a contextual implicit conversion. | |||
2828 | ExprResult PerformContextualImplicitConversion( | |||
2829 | SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); | |||
2830 | ||||
2831 | ||||
2832 | enum ObjCSubscriptKind { | |||
2833 | OS_Array, | |||
2834 | OS_Dictionary, | |||
2835 | OS_Error | |||
2836 | }; | |||
2837 | ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); | |||
2838 | ||||
2839 | // Note that LK_String is intentionally after the other literals, as | |||
2840 | // this is used for diagnostics logic. | |||
2841 | enum ObjCLiteralKind { | |||
2842 | LK_Array, | |||
2843 | LK_Dictionary, | |||
2844 | LK_Numeric, | |||
2845 | LK_Boxed, | |||
2846 | LK_String, | |||
2847 | LK_Block, | |||
2848 | LK_None | |||
2849 | }; | |||
2850 | ObjCLiteralKind CheckLiteralKind(Expr *FromE); | |||
2851 | ||||
2852 | ExprResult PerformObjectMemberConversion(Expr *From, | |||
2853 | NestedNameSpecifier *Qualifier, | |||
2854 | NamedDecl *FoundDecl, | |||
2855 | NamedDecl *Member); | |||
2856 | ||||
2857 | // Members have to be NamespaceDecl* or TranslationUnitDecl*. | |||
2858 | // TODO: make this is a typesafe union. | |||
2859 | typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; | |||
2860 | typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; | |||
2861 | ||||
2862 | using ADLCallKind = CallExpr::ADLCallKind; | |||
2863 | ||||
2864 | void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, | |||
2865 | ArrayRef<Expr *> Args, | |||
2866 | OverloadCandidateSet &CandidateSet, | |||
2867 | bool SuppressUserConversions = false, | |||
2868 | bool PartialOverloading = false, | |||
2869 | bool AllowExplicit = true, | |||
2870 | bool AllowExplicitConversion = false, | |||
2871 | ADLCallKind IsADLCandidate = ADLCallKind::NotADL, | |||
2872 | ConversionSequenceList EarlyConversions = None); | |||
2873 | void AddFunctionCandidates(const UnresolvedSetImpl &Functions, | |||
2874 | ArrayRef<Expr *> Args, | |||
2875 | OverloadCandidateSet &CandidateSet, | |||
2876 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, | |||
2877 | bool SuppressUserConversions = false, | |||
2878 | bool PartialOverloading = false, | |||
2879 | bool FirstArgumentIsBase = false); | |||
2880 | void AddMethodCandidate(DeclAccessPair FoundDecl, | |||
2881 | QualType ObjectType, | |||
2882 | Expr::Classification ObjectClassification, | |||
2883 | ArrayRef<Expr *> Args, | |||
2884 | OverloadCandidateSet& CandidateSet, | |||
2885 | bool SuppressUserConversion = false); | |||
2886 | void AddMethodCandidate(CXXMethodDecl *Method, | |||
2887 | DeclAccessPair FoundDecl, | |||
2888 | CXXRecordDecl *ActingContext, QualType ObjectType, | |||
2889 | Expr::Classification ObjectClassification, | |||
2890 | ArrayRef<Expr *> Args, | |||
2891 | OverloadCandidateSet& CandidateSet, | |||
2892 | bool SuppressUserConversions = false, | |||
2893 | bool PartialOverloading = false, | |||
2894 | ConversionSequenceList EarlyConversions = None); | |||
2895 | void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, | |||
2896 | DeclAccessPair FoundDecl, | |||
2897 | CXXRecordDecl *ActingContext, | |||
2898 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
2899 | QualType ObjectType, | |||
2900 | Expr::Classification ObjectClassification, | |||
2901 | ArrayRef<Expr *> Args, | |||
2902 | OverloadCandidateSet& CandidateSet, | |||
2903 | bool SuppressUserConversions = false, | |||
2904 | bool PartialOverloading = false); | |||
2905 | void AddTemplateOverloadCandidate( | |||
2906 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, | |||
2907 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, | |||
2908 | OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, | |||
2909 | bool PartialOverloading = false, bool AllowExplicit = true, | |||
2910 | ADLCallKind IsADLCandidate = ADLCallKind::NotADL); | |||
2911 | bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, | |||
2912 | ArrayRef<QualType> ParamTypes, | |||
2913 | ArrayRef<Expr *> Args, | |||
2914 | OverloadCandidateSet &CandidateSet, | |||
2915 | ConversionSequenceList &Conversions, | |||
2916 | bool SuppressUserConversions, | |||
2917 | CXXRecordDecl *ActingContext = nullptr, | |||
2918 | QualType ObjectType = QualType(), | |||
2919 | Expr::Classification | |||
2920 | ObjectClassification = {}); | |||
2921 | void AddConversionCandidate( | |||
2922 | CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, | |||
2923 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, | |||
2924 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, | |||
2925 | bool AllowExplicit, bool AllowResultConversion = true); | |||
2926 | void AddTemplateConversionCandidate( | |||
2927 | FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, | |||
2928 | CXXRecordDecl *ActingContext, Expr *From, QualType ToType, | |||
2929 | OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, | |||
2930 | bool AllowExplicit, bool AllowResultConversion = true); | |||
2931 | void AddSurrogateCandidate(CXXConversionDecl *Conversion, | |||
2932 | DeclAccessPair FoundDecl, | |||
2933 | CXXRecordDecl *ActingContext, | |||
2934 | const FunctionProtoType *Proto, | |||
2935 | Expr *Object, ArrayRef<Expr *> Args, | |||
2936 | OverloadCandidateSet& CandidateSet); | |||
2937 | void AddMemberOperatorCandidates(OverloadedOperatorKind Op, | |||
2938 | SourceLocation OpLoc, ArrayRef<Expr *> Args, | |||
2939 | OverloadCandidateSet& CandidateSet, | |||
2940 | SourceRange OpRange = SourceRange()); | |||
2941 | void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, | |||
2942 | OverloadCandidateSet& CandidateSet, | |||
2943 | bool IsAssignmentOperator = false, | |||
2944 | unsigned NumContextualBoolArguments = 0); | |||
2945 | void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, | |||
2946 | SourceLocation OpLoc, ArrayRef<Expr *> Args, | |||
2947 | OverloadCandidateSet& CandidateSet); | |||
2948 | void AddArgumentDependentLookupCandidates(DeclarationName Name, | |||
2949 | SourceLocation Loc, | |||
2950 | ArrayRef<Expr *> Args, | |||
2951 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
2952 | OverloadCandidateSet& CandidateSet, | |||
2953 | bool PartialOverloading = false); | |||
2954 | ||||
2955 | // Emit as a 'note' the specific overload candidate | |||
2956 | void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, | |||
2957 | QualType DestType = QualType(), | |||
2958 | bool TakingAddress = false); | |||
2959 | ||||
2960 | // Emit as a series of 'note's all template and non-templates identified by | |||
2961 | // the expression Expr | |||
2962 | void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), | |||
2963 | bool TakingAddress = false); | |||
2964 | ||||
2965 | /// Check the enable_if expressions on the given function. Returns the first | |||
2966 | /// failing attribute, or NULL if they were all successful. | |||
2967 | EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, | |||
2968 | bool MissingImplicitThis = false); | |||
2969 | ||||
2970 | /// Find the failed Boolean condition within a given Boolean | |||
2971 | /// constant expression, and describe it with a string. | |||
2972 | std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); | |||
2973 | ||||
2974 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any | |||
2975 | /// non-ArgDependent DiagnoseIfAttrs. | |||
2976 | /// | |||
2977 | /// Argument-dependent diagnose_if attributes should be checked each time a | |||
2978 | /// function is used as a direct callee of a function call. | |||
2979 | /// | |||
2980 | /// Returns true if any errors were emitted. | |||
2981 | bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, | |||
2982 | const Expr *ThisArg, | |||
2983 | ArrayRef<const Expr *> Args, | |||
2984 | SourceLocation Loc); | |||
2985 | ||||
2986 | /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any | |||
2987 | /// ArgDependent DiagnoseIfAttrs. | |||
2988 | /// | |||
2989 | /// Argument-independent diagnose_if attributes should be checked on every use | |||
2990 | /// of a function. | |||
2991 | /// | |||
2992 | /// Returns true if any errors were emitted. | |||
2993 | bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, | |||
2994 | SourceLocation Loc); | |||
2995 | ||||
2996 | /// Returns whether the given function's address can be taken or not, | |||
2997 | /// optionally emitting a diagnostic if the address can't be taken. | |||
2998 | /// | |||
2999 | /// Returns false if taking the address of the function is illegal. | |||
3000 | bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, | |||
3001 | bool Complain = false, | |||
3002 | SourceLocation Loc = SourceLocation()); | |||
3003 | ||||
3004 | // [PossiblyAFunctionType] --> [Return] | |||
3005 | // NonFunctionType --> NonFunctionType | |||
3006 | // R (A) --> R(A) | |||
3007 | // R (*)(A) --> R (A) | |||
3008 | // R (&)(A) --> R (A) | |||
3009 | // R (S::*)(A) --> R (A) | |||
3010 | QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); | |||
3011 | ||||
3012 | FunctionDecl * | |||
3013 | ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, | |||
3014 | QualType TargetType, | |||
3015 | bool Complain, | |||
3016 | DeclAccessPair &Found, | |||
3017 | bool *pHadMultipleCandidates = nullptr); | |||
3018 | ||||
3019 | FunctionDecl * | |||
3020 | resolveAddressOfOnlyViableOverloadCandidate(Expr *E, | |||
3021 | DeclAccessPair &FoundResult); | |||
3022 | ||||
3023 | bool resolveAndFixAddressOfOnlyViableOverloadCandidate( | |||
3024 | ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); | |||
3025 | ||||
3026 | FunctionDecl * | |||
3027 | ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, | |||
3028 | bool Complain = false, | |||
3029 | DeclAccessPair *Found = nullptr); | |||
3030 | ||||
3031 | bool ResolveAndFixSingleFunctionTemplateSpecialization( | |||
3032 | ExprResult &SrcExpr, | |||
3033 | bool DoFunctionPointerConverion = false, | |||
3034 | bool Complain = false, | |||
3035 | SourceRange OpRangeForComplaining = SourceRange(), | |||
3036 | QualType DestTypeForComplaining = QualType(), | |||
3037 | unsigned DiagIDForComplaining = 0); | |||
3038 | ||||
3039 | ||||
3040 | Expr *FixOverloadedFunctionReference(Expr *E, | |||
3041 | DeclAccessPair FoundDecl, | |||
3042 | FunctionDecl *Fn); | |||
3043 | ExprResult FixOverloadedFunctionReference(ExprResult, | |||
3044 | DeclAccessPair FoundDecl, | |||
3045 | FunctionDecl *Fn); | |||
3046 | ||||
3047 | void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, | |||
3048 | ArrayRef<Expr *> Args, | |||
3049 | OverloadCandidateSet &CandidateSet, | |||
3050 | bool PartialOverloading = false); | |||
3051 | ||||
3052 | // An enum used to represent the different possible results of building a | |||
3053 | // range-based for loop. | |||
3054 | enum ForRangeStatus { | |||
3055 | FRS_Success, | |||
3056 | FRS_NoViableFunction, | |||
3057 | FRS_DiagnosticIssued | |||
3058 | }; | |||
3059 | ||||
3060 | ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, | |||
3061 | SourceLocation RangeLoc, | |||
3062 | const DeclarationNameInfo &NameInfo, | |||
3063 | LookupResult &MemberLookup, | |||
3064 | OverloadCandidateSet *CandidateSet, | |||
3065 | Expr *Range, ExprResult *CallExpr); | |||
3066 | ||||
3067 | ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, | |||
3068 | UnresolvedLookupExpr *ULE, | |||
3069 | SourceLocation LParenLoc, | |||
3070 | MultiExprArg Args, | |||
3071 | SourceLocation RParenLoc, | |||
3072 | Expr *ExecConfig, | |||
3073 | bool AllowTypoCorrection=true, | |||
3074 | bool CalleesAddressIsTaken=false); | |||
3075 | ||||
3076 | bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, | |||
3077 | MultiExprArg Args, SourceLocation RParenLoc, | |||
3078 | OverloadCandidateSet *CandidateSet, | |||
3079 | ExprResult *Result); | |||
3080 | ||||
3081 | ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, | |||
3082 | UnaryOperatorKind Opc, | |||
3083 | const UnresolvedSetImpl &Fns, | |||
3084 | Expr *input, bool RequiresADL = true); | |||
3085 | ||||
3086 | ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, | |||
3087 | BinaryOperatorKind Opc, | |||
3088 | const UnresolvedSetImpl &Fns, | |||
3089 | Expr *LHS, Expr *RHS, | |||
3090 | bool RequiresADL = true); | |||
3091 | ||||
3092 | ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, | |||
3093 | SourceLocation RLoc, | |||
3094 | Expr *Base,Expr *Idx); | |||
3095 | ||||
3096 | ExprResult | |||
3097 | BuildCallToMemberFunction(Scope *S, Expr *MemExpr, | |||
3098 | SourceLocation LParenLoc, | |||
3099 | MultiExprArg Args, | |||
3100 | SourceLocation RParenLoc); | |||
3101 | ExprResult | |||
3102 | BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, | |||
3103 | MultiExprArg Args, | |||
3104 | SourceLocation RParenLoc); | |||
3105 | ||||
3106 | ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, | |||
3107 | SourceLocation OpLoc, | |||
3108 | bool *NoArrowOperatorFound = nullptr); | |||
3109 | ||||
3110 | /// CheckCallReturnType - Checks that a call expression's return type is | |||
3111 | /// complete. Returns true on failure. The location passed in is the location | |||
3112 | /// that best represents the call. | |||
3113 | bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, | |||
3114 | CallExpr *CE, FunctionDecl *FD); | |||
3115 | ||||
3116 | /// Helpers for dealing with blocks and functions. | |||
3117 | bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, | |||
3118 | bool CheckParameterNames); | |||
3119 | void CheckCXXDefaultArguments(FunctionDecl *FD); | |||
3120 | void CheckExtraCXXDefaultArguments(Declarator &D); | |||
3121 | Scope *getNonFieldDeclScope(Scope *S); | |||
3122 | ||||
3123 | /// \name Name lookup | |||
3124 | /// | |||
3125 | /// These routines provide name lookup that is used during semantic | |||
3126 | /// analysis to resolve the various kinds of names (identifiers, | |||
3127 | /// overloaded operator names, constructor names, etc.) into zero or | |||
3128 | /// more declarations within a particular scope. The major entry | |||
3129 | /// points are LookupName, which performs unqualified name lookup, | |||
3130 | /// and LookupQualifiedName, which performs qualified name lookup. | |||
3131 | /// | |||
3132 | /// All name lookup is performed based on some specific criteria, | |||
3133 | /// which specify what names will be visible to name lookup and how | |||
3134 | /// far name lookup should work. These criteria are important both | |||
3135 | /// for capturing language semantics (certain lookups will ignore | |||
3136 | /// certain names, for example) and for performance, since name | |||
3137 | /// lookup is often a bottleneck in the compilation of C++. Name | |||
3138 | /// lookup criteria is specified via the LookupCriteria enumeration. | |||
3139 | /// | |||
3140 | /// The results of name lookup can vary based on the kind of name | |||
3141 | /// lookup performed, the current language, and the translation | |||
3142 | /// unit. In C, for example, name lookup will either return nothing | |||
3143 | /// (no entity found) or a single declaration. In C++, name lookup | |||
3144 | /// can additionally refer to a set of overloaded functions or | |||
3145 | /// result in an ambiguity. All of the possible results of name | |||
3146 | /// lookup are captured by the LookupResult class, which provides | |||
3147 | /// the ability to distinguish among them. | |||
3148 | //@{ | |||
3149 | ||||
3150 | /// Describes the kind of name lookup to perform. | |||
3151 | enum LookupNameKind { | |||
3152 | /// Ordinary name lookup, which finds ordinary names (functions, | |||
3153 | /// variables, typedefs, etc.) in C and most kinds of names | |||
3154 | /// (functions, variables, members, types, etc.) in C++. | |||
3155 | LookupOrdinaryName = 0, | |||
3156 | /// Tag name lookup, which finds the names of enums, classes, | |||
3157 | /// structs, and unions. | |||
3158 | LookupTagName, | |||
3159 | /// Label name lookup. | |||
3160 | LookupLabel, | |||
3161 | /// Member name lookup, which finds the names of | |||
3162 | /// class/struct/union members. | |||
3163 | LookupMemberName, | |||
3164 | /// Look up of an operator name (e.g., operator+) for use with | |||
3165 | /// operator overloading. This lookup is similar to ordinary name | |||
3166 | /// lookup, but will ignore any declarations that are class members. | |||
3167 | LookupOperatorName, | |||
3168 | /// Look up of a name that precedes the '::' scope resolution | |||
3169 | /// operator in C++. This lookup completely ignores operator, object, | |||
3170 | /// function, and enumerator names (C++ [basic.lookup.qual]p1). | |||
3171 | LookupNestedNameSpecifierName, | |||
3172 | /// Look up a namespace name within a C++ using directive or | |||
3173 | /// namespace alias definition, ignoring non-namespace names (C++ | |||
3174 | /// [basic.lookup.udir]p1). | |||
3175 | LookupNamespaceName, | |||
3176 | /// Look up all declarations in a scope with the given name, | |||
3177 | /// including resolved using declarations. This is appropriate | |||
3178 | /// for checking redeclarations for a using declaration. | |||
3179 | LookupUsingDeclName, | |||
3180 | /// Look up an ordinary name that is going to be redeclared as a | |||
3181 | /// name with linkage. This lookup ignores any declarations that | |||
3182 | /// are outside of the current scope unless they have linkage. See | |||
3183 | /// C99 6.2.2p4-5 and C++ [basic.link]p6. | |||
3184 | LookupRedeclarationWithLinkage, | |||
3185 | /// Look up a friend of a local class. This lookup does not look | |||
3186 | /// outside the innermost non-class scope. See C++11 [class.friend]p11. | |||
3187 | LookupLocalFriendName, | |||
3188 | /// Look up the name of an Objective-C protocol. | |||
3189 | LookupObjCProtocolName, | |||
3190 | /// Look up implicit 'self' parameter of an objective-c method. | |||
3191 | LookupObjCImplicitSelfParam, | |||
3192 | /// Look up the name of an OpenMP user-defined reduction operation. | |||
3193 | LookupOMPReductionName, | |||
3194 | /// Look up the name of an OpenMP user-defined mapper. | |||
3195 | LookupOMPMapperName, | |||
3196 | /// Look up any declaration with any name. | |||
3197 | LookupAnyName | |||
3198 | }; | |||
3199 | ||||
3200 | /// Specifies whether (or how) name lookup is being performed for a | |||
3201 | /// redeclaration (vs. a reference). | |||
3202 | enum RedeclarationKind { | |||
3203 | /// The lookup is a reference to this name that is not for the | |||
3204 | /// purpose of redeclaring the name. | |||
3205 | NotForRedeclaration = 0, | |||
3206 | /// The lookup results will be used for redeclaration of a name, | |||
3207 | /// if an entity by that name already exists and is visible. | |||
3208 | ForVisibleRedeclaration, | |||
3209 | /// The lookup results will be used for redeclaration of a name | |||
3210 | /// with external linkage; non-visible lookup results with external linkage | |||
3211 | /// may also be found. | |||
3212 | ForExternalRedeclaration | |||
3213 | }; | |||
3214 | ||||
3215 | RedeclarationKind forRedeclarationInCurContext() { | |||
3216 | // A declaration with an owning module for linkage can never link against | |||
3217 | // anything that is not visible. We don't need to check linkage here; if | |||
3218 | // the context has internal linkage, redeclaration lookup won't find things | |||
3219 | // from other TUs, and we can't safely compute linkage yet in general. | |||
3220 | if (cast<Decl>(CurContext) | |||
3221 | ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) | |||
3222 | return ForVisibleRedeclaration; | |||
3223 | return ForExternalRedeclaration; | |||
3224 | } | |||
3225 | ||||
3226 | /// The possible outcomes of name lookup for a literal operator. | |||
3227 | enum LiteralOperatorLookupResult { | |||
3228 | /// The lookup resulted in an error. | |||
3229 | LOLR_Error, | |||
3230 | /// The lookup found no match but no diagnostic was issued. | |||
3231 | LOLR_ErrorNoDiagnostic, | |||
3232 | /// The lookup found a single 'cooked' literal operator, which | |||
3233 | /// expects a normal literal to be built and passed to it. | |||
3234 | LOLR_Cooked, | |||
3235 | /// The lookup found a single 'raw' literal operator, which expects | |||
3236 | /// a string literal containing the spelling of the literal token. | |||
3237 | LOLR_Raw, | |||
3238 | /// The lookup found an overload set of literal operator templates, | |||
3239 | /// which expect the characters of the spelling of the literal token to be | |||
3240 | /// passed as a non-type template argument pack. | |||
3241 | LOLR_Template, | |||
3242 | /// The lookup found an overload set of literal operator templates, | |||
3243 | /// which expect the character type and characters of the spelling of the | |||
3244 | /// string literal token to be passed as template arguments. | |||
3245 | LOLR_StringTemplate | |||
3246 | }; | |||
3247 | ||||
3248 | SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, | |||
3249 | CXXSpecialMember SM, | |||
3250 | bool ConstArg, | |||
3251 | bool VolatileArg, | |||
3252 | bool RValueThis, | |||
3253 | bool ConstThis, | |||
3254 | bool VolatileThis); | |||
3255 | ||||
3256 | typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; | |||
3257 | typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> | |||
3258 | TypoRecoveryCallback; | |||
3259 | ||||
3260 | private: | |||
3261 | bool CppLookupName(LookupResult &R, Scope *S); | |||
3262 | ||||
3263 | struct TypoExprState { | |||
3264 | std::unique_ptr<TypoCorrectionConsumer> Consumer; | |||
3265 | TypoDiagnosticGenerator DiagHandler; | |||
3266 | TypoRecoveryCallback RecoveryHandler; | |||
3267 | TypoExprState(); | |||
3268 | TypoExprState(TypoExprState &&other) noexcept; | |||
3269 | TypoExprState &operator=(TypoExprState &&other) noexcept; | |||
3270 | }; | |||
3271 | ||||
3272 | /// The set of unhandled TypoExprs and their associated state. | |||
3273 | llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; | |||
3274 | ||||
3275 | /// Creates a new TypoExpr AST node. | |||
3276 | TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, | |||
3277 | TypoDiagnosticGenerator TDG, | |||
3278 | TypoRecoveryCallback TRC); | |||
3279 | ||||
3280 | // The set of known/encountered (unique, canonicalized) NamespaceDecls. | |||
3281 | // | |||
3282 | // The boolean value will be true to indicate that the namespace was loaded | |||
3283 | // from an AST/PCH file, or false otherwise. | |||
3284 | llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; | |||
3285 | ||||
3286 | /// Whether we have already loaded known namespaces from an extenal | |||
3287 | /// source. | |||
3288 | bool LoadedExternalKnownNamespaces; | |||
3289 | ||||
3290 | /// Helper for CorrectTypo and CorrectTypoDelayed used to create and | |||
3291 | /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction | |||
3292 | /// should be skipped entirely. | |||
3293 | std::unique_ptr<TypoCorrectionConsumer> | |||
3294 | makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, | |||
3295 | Sema::LookupNameKind LookupKind, Scope *S, | |||
3296 | CXXScopeSpec *SS, | |||
3297 | CorrectionCandidateCallback &CCC, | |||
3298 | DeclContext *MemberContext, bool EnteringContext, | |||
3299 | const ObjCObjectPointerType *OPT, | |||
3300 | bool ErrorRecovery); | |||
3301 | ||||
3302 | public: | |||
3303 | const TypoExprState &getTypoExprState(TypoExpr *TE) const; | |||
3304 | ||||
3305 | /// Clears the state of the given TypoExpr. | |||
3306 | void clearDelayedTypo(TypoExpr *TE); | |||
3307 | ||||
3308 | /// Look up a name, looking for a single declaration. Return | |||
3309 | /// null if the results were absent, ambiguous, or overloaded. | |||
3310 | /// | |||
3311 | /// It is preferable to use the elaborated form and explicitly handle | |||
3312 | /// ambiguity and overloaded. | |||
3313 | NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, | |||
3314 | SourceLocation Loc, | |||
3315 | LookupNameKind NameKind, | |||
3316 | RedeclarationKind Redecl | |||
3317 | = NotForRedeclaration); | |||
3318 | bool LookupName(LookupResult &R, Scope *S, | |||
3319 | bool AllowBuiltinCreation = false); | |||
3320 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, | |||
3321 | bool InUnqualifiedLookup = false); | |||
3322 | bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, | |||
3323 | CXXScopeSpec &SS); | |||
3324 | bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, | |||
3325 | bool AllowBuiltinCreation = false, | |||
3326 | bool EnteringContext = false); | |||
3327 | ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, | |||
3328 | RedeclarationKind Redecl | |||
3329 | = NotForRedeclaration); | |||
3330 | bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); | |||
3331 | ||||
3332 | void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, | |||
3333 | QualType T1, QualType T2, | |||
3334 | UnresolvedSetImpl &Functions); | |||
3335 | ||||
3336 | LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, | |||
3337 | SourceLocation GnuLabelLoc = SourceLocation()); | |||
3338 | ||||
3339 | DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); | |||
3340 | CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); | |||
3341 | CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, | |||
3342 | unsigned Quals); | |||
3343 | CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, | |||
3344 | bool RValueThis, unsigned ThisQuals); | |||
3345 | CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, | |||
3346 | unsigned Quals); | |||
3347 | CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, | |||
3348 | bool RValueThis, unsigned ThisQuals); | |||
3349 | CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); | |||
3350 | ||||
3351 | bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); | |||
3352 | LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, | |||
3353 | ArrayRef<QualType> ArgTys, | |||
3354 | bool AllowRaw, | |||
3355 | bool AllowTemplate, | |||
3356 | bool AllowStringTemplate, | |||
3357 | bool DiagnoseMissing); | |||
3358 | bool isKnownName(StringRef name); | |||
3359 | ||||
3360 | void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, | |||
3361 | ArrayRef<Expr *> Args, ADLResult &Functions); | |||
3362 | ||||
3363 | void LookupVisibleDecls(Scope *S, LookupNameKind Kind, | |||
3364 | VisibleDeclConsumer &Consumer, | |||
3365 | bool IncludeGlobalScope = true, | |||
3366 | bool LoadExternal = true); | |||
3367 | void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, | |||
3368 | VisibleDeclConsumer &Consumer, | |||
3369 | bool IncludeGlobalScope = true, | |||
3370 | bool IncludeDependentBases = false, | |||
3371 | bool LoadExternal = true); | |||
3372 | ||||
3373 | enum CorrectTypoKind { | |||
3374 | CTK_NonError, // CorrectTypo used in a non error recovery situation. | |||
3375 | CTK_ErrorRecovery // CorrectTypo used in normal error recovery. | |||
3376 | }; | |||
3377 | ||||
3378 | TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, | |||
3379 | Sema::LookupNameKind LookupKind, | |||
3380 | Scope *S, CXXScopeSpec *SS, | |||
3381 | CorrectionCandidateCallback &CCC, | |||
3382 | CorrectTypoKind Mode, | |||
3383 | DeclContext *MemberContext = nullptr, | |||
3384 | bool EnteringContext = false, | |||
3385 | const ObjCObjectPointerType *OPT = nullptr, | |||
3386 | bool RecordFailure = true); | |||
3387 | ||||
3388 | TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, | |||
3389 | Sema::LookupNameKind LookupKind, Scope *S, | |||
3390 | CXXScopeSpec *SS, | |||
3391 | CorrectionCandidateCallback &CCC, | |||
3392 | TypoDiagnosticGenerator TDG, | |||
3393 | TypoRecoveryCallback TRC, CorrectTypoKind Mode, | |||
3394 | DeclContext *MemberContext = nullptr, | |||
3395 | bool EnteringContext = false, | |||
3396 | const ObjCObjectPointerType *OPT = nullptr); | |||
3397 | ||||
3398 | /// Process any TypoExprs in the given Expr and its children, | |||
3399 | /// generating diagnostics as appropriate and returning a new Expr if there | |||
3400 | /// were typos that were all successfully corrected and ExprError if one or | |||
3401 | /// more typos could not be corrected. | |||
3402 | /// | |||
3403 | /// \param E The Expr to check for TypoExprs. | |||
3404 | /// | |||
3405 | /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its | |||
3406 | /// initializer. | |||
3407 | /// | |||
3408 | /// \param Filter A function applied to a newly rebuilt Expr to determine if | |||
3409 | /// it is an acceptable/usable result from a single combination of typo | |||
3410 | /// corrections. As long as the filter returns ExprError, different | |||
3411 | /// combinations of corrections will be tried until all are exhausted. | |||
3412 | ExprResult | |||
3413 | CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, | |||
3414 | llvm::function_ref<ExprResult(Expr *)> Filter = | |||
3415 | [](Expr *E) -> ExprResult { return E; }); | |||
3416 | ||||
3417 | ExprResult | |||
3418 | CorrectDelayedTyposInExpr(Expr *E, | |||
3419 | llvm::function_ref<ExprResult(Expr *)> Filter) { | |||
3420 | return CorrectDelayedTyposInExpr(E, nullptr, Filter); | |||
3421 | } | |||
3422 | ||||
3423 | ExprResult | |||
3424 | CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, | |||
3425 | llvm::function_ref<ExprResult(Expr *)> Filter = | |||
3426 | [](Expr *E) -> ExprResult { return E; }) { | |||
3427 | return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); | |||
3428 | } | |||
3429 | ||||
3430 | ExprResult | |||
3431 | CorrectDelayedTyposInExpr(ExprResult ER, | |||
3432 | llvm::function_ref<ExprResult(Expr *)> Filter) { | |||
3433 | return CorrectDelayedTyposInExpr(ER, nullptr, Filter); | |||
3434 | } | |||
3435 | ||||
3436 | void diagnoseTypo(const TypoCorrection &Correction, | |||
3437 | const PartialDiagnostic &TypoDiag, | |||
3438 | bool ErrorRecovery = true); | |||
3439 | ||||
3440 | void diagnoseTypo(const TypoCorrection &Correction, | |||
3441 | const PartialDiagnostic &TypoDiag, | |||
3442 | const PartialDiagnostic &PrevNote, | |||
3443 | bool ErrorRecovery = true); | |||
3444 | ||||
3445 | void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); | |||
3446 | ||||
3447 | void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, | |||
3448 | ArrayRef<Expr *> Args, | |||
3449 | AssociatedNamespaceSet &AssociatedNamespaces, | |||
3450 | AssociatedClassSet &AssociatedClasses); | |||
3451 | ||||
3452 | void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | |||
3453 | bool ConsiderLinkage, bool AllowInlineNamespace); | |||
3454 | ||||
3455 | bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); | |||
3456 | ||||
3457 | void DiagnoseAmbiguousLookup(LookupResult &Result); | |||
3458 | //@} | |||
3459 | ||||
3460 | ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, | |||
3461 | SourceLocation IdLoc, | |||
3462 | bool TypoCorrection = false); | |||
3463 | NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | |||
3464 | Scope *S, bool ForRedeclaration, | |||
3465 | SourceLocation Loc); | |||
3466 | NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, | |||
3467 | Scope *S); | |||
3468 | void AddKnownFunctionAttributes(FunctionDecl *FD); | |||
3469 | ||||
3470 | // More parsing and symbol table subroutines. | |||
3471 | ||||
3472 | void ProcessPragmaWeak(Scope *S, Decl *D); | |||
3473 | // Decl attributes - this routine is the top level dispatcher. | |||
3474 | void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); | |||
3475 | // Helper for delayed processing of attributes. | |||
3476 | void ProcessDeclAttributeDelayed(Decl *D, | |||
3477 | const ParsedAttributesView &AttrList); | |||
3478 | void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, | |||
3479 | bool IncludeCXX11Attributes = true); | |||
3480 | bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, | |||
3481 | const ParsedAttributesView &AttrList); | |||
3482 | ||||
3483 | void checkUnusedDeclAttributes(Declarator &D); | |||
3484 | ||||
3485 | /// Determine if type T is a valid subject for a nonnull and similar | |||
3486 | /// attributes. By default, we look through references (the behavior used by | |||
3487 | /// nonnull), but if the second parameter is true, then we treat a reference | |||
3488 | /// type as valid. | |||
3489 | bool isValidPointerAttrType(QualType T, bool RefOkay = false); | |||
3490 | ||||
3491 | bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); | |||
3492 | bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, | |||
3493 | const FunctionDecl *FD = nullptr); | |||
3494 | bool CheckAttrTarget(const ParsedAttr &CurrAttr); | |||
3495 | bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); | |||
3496 | bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, | |||
3497 | StringRef &Str, | |||
3498 | SourceLocation *ArgLocation = nullptr); | |||
3499 | bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); | |||
3500 | bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); | |||
3501 | bool checkMSInheritanceAttrOnDefinition( | |||
3502 | CXXRecordDecl *RD, SourceRange Range, bool BestCase, | |||
3503 | MSInheritanceAttr::Spelling SemanticSpelling); | |||
3504 | ||||
3505 | void CheckAlignasUnderalignment(Decl *D); | |||
3506 | ||||
3507 | /// Adjust the calling convention of a method to be the ABI default if it | |||
3508 | /// wasn't specified explicitly. This handles method types formed from | |||
3509 | /// function type typedefs and typename template arguments. | |||
3510 | void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, | |||
3511 | SourceLocation Loc); | |||
3512 | ||||
3513 | // Check if there is an explicit attribute, but only look through parens. | |||
3514 | // The intent is to look for an attribute on the current declarator, but not | |||
3515 | // one that came from a typedef. | |||
3516 | bool hasExplicitCallingConv(QualType T); | |||
3517 | ||||
3518 | /// Get the outermost AttributedType node that sets a calling convention. | |||
3519 | /// Valid types should not have multiple attributes with different CCs. | |||
3520 | const AttributedType *getCallingConvAttributedType(QualType T) const; | |||
3521 | ||||
3522 | /// Stmt attributes - this routine is the top level dispatcher. | |||
3523 | StmtResult ProcessStmtAttributes(Stmt *Stmt, | |||
3524 | const ParsedAttributesView &Attrs, | |||
3525 | SourceRange Range); | |||
3526 | ||||
3527 | void WarnConflictingTypedMethods(ObjCMethodDecl *Method, | |||
3528 | ObjCMethodDecl *MethodDecl, | |||
3529 | bool IsProtocolMethodDecl); | |||
3530 | ||||
3531 | void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, | |||
3532 | ObjCMethodDecl *Overridden, | |||
3533 | bool IsProtocolMethodDecl); | |||
3534 | ||||
3535 | /// WarnExactTypedMethods - This routine issues a warning if method | |||
3536 | /// implementation declaration matches exactly that of its declaration. | |||
3537 | void WarnExactTypedMethods(ObjCMethodDecl *Method, | |||
3538 | ObjCMethodDecl *MethodDecl, | |||
3539 | bool IsProtocolMethodDecl); | |||
3540 | ||||
3541 | typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; | |||
3542 | ||||
3543 | /// CheckImplementationIvars - This routine checks if the instance variables | |||
3544 | /// listed in the implelementation match those listed in the interface. | |||
3545 | void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, | |||
3546 | ObjCIvarDecl **Fields, unsigned nIvars, | |||
3547 | SourceLocation Loc); | |||
3548 | ||||
3549 | /// ImplMethodsVsClassMethods - This is main routine to warn if any method | |||
3550 | /// remains unimplemented in the class or category \@implementation. | |||
3551 | void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, | |||
3552 | ObjCContainerDecl* IDecl, | |||
3553 | bool IncompleteImpl = false); | |||
3554 | ||||
3555 | /// DiagnoseUnimplementedProperties - This routine warns on those properties | |||
3556 | /// which must be implemented by this implementation. | |||
3557 | void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, | |||
3558 | ObjCContainerDecl *CDecl, | |||
3559 | bool SynthesizeProperties); | |||
3560 | ||||
3561 | /// Diagnose any null-resettable synthesized setters. | |||
3562 | void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); | |||
3563 | ||||
3564 | /// DefaultSynthesizeProperties - This routine default synthesizes all | |||
3565 | /// properties which must be synthesized in the class's \@implementation. | |||
3566 | void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, | |||
3567 | ObjCInterfaceDecl *IDecl, | |||
3568 | SourceLocation AtEnd); | |||
3569 | void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); | |||
3570 | ||||
3571 | /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is | |||
3572 | /// an ivar synthesized for 'Method' and 'Method' is a property accessor | |||
3573 | /// declared in class 'IFace'. | |||
3574 | bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, | |||
3575 | ObjCMethodDecl *Method, ObjCIvarDecl *IV); | |||
3576 | ||||
3577 | /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which | |||
3578 | /// backs the property is not used in the property's accessor. | |||
3579 | void DiagnoseUnusedBackingIvarInAccessor(Scope *S, | |||
3580 | const ObjCImplementationDecl *ImplD); | |||
3581 | ||||
3582 | /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and | |||
3583 | /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. | |||
3584 | /// It also returns ivar's property on success. | |||
3585 | ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, | |||
3586 | const ObjCPropertyDecl *&PDecl) const; | |||
3587 | ||||
3588 | /// Called by ActOnProperty to handle \@property declarations in | |||
3589 | /// class extensions. | |||
3590 | ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, | |||
3591 | SourceLocation AtLoc, | |||
3592 | SourceLocation LParenLoc, | |||
3593 | FieldDeclarator &FD, | |||
3594 | Selector GetterSel, | |||
3595 | SourceLocation GetterNameLoc, | |||
3596 | Selector SetterSel, | |||
3597 | SourceLocation SetterNameLoc, | |||
3598 | const bool isReadWrite, | |||
3599 | unsigned &Attributes, | |||
3600 | const unsigned AttributesAsWritten, | |||
3601 | QualType T, | |||
3602 | TypeSourceInfo *TSI, | |||
3603 | tok::ObjCKeywordKind MethodImplKind); | |||
3604 | ||||
3605 | /// Called by ActOnProperty and HandlePropertyInClassExtension to | |||
3606 | /// handle creating the ObjcPropertyDecl for a category or \@interface. | |||
3607 | ObjCPropertyDecl *CreatePropertyDecl(Scope *S, | |||
3608 | ObjCContainerDecl *CDecl, | |||
3609 | SourceLocation AtLoc, | |||
3610 | SourceLocation LParenLoc, | |||
3611 | FieldDeclarator &FD, | |||
3612 | Selector GetterSel, | |||
3613 | SourceLocation GetterNameLoc, | |||
3614 | Selector SetterSel, | |||
3615 | SourceLocation SetterNameLoc, | |||
3616 | const bool isReadWrite, | |||
3617 | const unsigned Attributes, | |||
3618 | const unsigned AttributesAsWritten, | |||
3619 | QualType T, | |||
3620 | TypeSourceInfo *TSI, | |||
3621 | tok::ObjCKeywordKind MethodImplKind, | |||
3622 | DeclContext *lexicalDC = nullptr); | |||
3623 | ||||
3624 | /// AtomicPropertySetterGetterRules - This routine enforces the rule (via | |||
3625 | /// warning) when atomic property has one but not the other user-declared | |||
3626 | /// setter or getter. | |||
3627 | void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, | |||
3628 | ObjCInterfaceDecl* IDecl); | |||
3629 | ||||
3630 | void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); | |||
3631 | ||||
3632 | void DiagnoseMissingDesignatedInitOverrides( | |||
3633 | const ObjCImplementationDecl *ImplD, | |||
3634 | const ObjCInterfaceDecl *IFD); | |||
3635 | ||||
3636 | void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); | |||
3637 | ||||
3638 | enum MethodMatchStrategy { | |||
3639 | MMS_loose, | |||
3640 | MMS_strict | |||
3641 | }; | |||
3642 | ||||
3643 | /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns | |||
3644 | /// true, or false, accordingly. | |||
3645 | bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, | |||
3646 | const ObjCMethodDecl *PrevMethod, | |||
3647 | MethodMatchStrategy strategy = MMS_strict); | |||
3648 | ||||
3649 | /// MatchAllMethodDeclarations - Check methods declaraed in interface or | |||
3650 | /// or protocol against those declared in their implementations. | |||
3651 | void MatchAllMethodDeclarations(const SelectorSet &InsMap, | |||
3652 | const SelectorSet &ClsMap, | |||
3653 | SelectorSet &InsMapSeen, | |||
3654 | SelectorSet &ClsMapSeen, | |||
3655 | ObjCImplDecl* IMPDecl, | |||
3656 | ObjCContainerDecl* IDecl, | |||
3657 | bool &IncompleteImpl, | |||
3658 | bool ImmediateClass, | |||
3659 | bool WarnCategoryMethodImpl=false); | |||
3660 | ||||
3661 | /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in | |||
3662 | /// category matches with those implemented in its primary class and | |||
3663 | /// warns each time an exact match is found. | |||
3664 | void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); | |||
3665 | ||||
3666 | /// Add the given method to the list of globally-known methods. | |||
3667 | void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); | |||
3668 | ||||
3669 | private: | |||
3670 | /// AddMethodToGlobalPool - Add an instance or factory method to the global | |||
3671 | /// pool. See descriptoin of AddInstanceMethodToGlobalPool. | |||
3672 | void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); | |||
3673 | ||||
3674 | /// LookupMethodInGlobalPool - Returns the instance or factory method and | |||
3675 | /// optionally warns if there are multiple signatures. | |||
3676 | ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, | |||
3677 | bool receiverIdOrClass, | |||
3678 | bool instance); | |||
3679 | ||||
3680 | public: | |||
3681 | /// - Returns instance or factory methods in global method pool for | |||
3682 | /// given selector. It checks the desired kind first, if none is found, and | |||
3683 | /// parameter checkTheOther is set, it then checks the other kind. If no such | |||
3684 | /// method or only one method is found, function returns false; otherwise, it | |||
3685 | /// returns true. | |||
3686 | bool | |||
3687 | CollectMultipleMethodsInGlobalPool(Selector Sel, | |||
3688 | SmallVectorImpl<ObjCMethodDecl*>& Methods, | |||
3689 | bool InstanceFirst, bool CheckTheOther, | |||
3690 | const ObjCObjectType *TypeBound = nullptr); | |||
3691 | ||||
3692 | bool | |||
3693 | AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, | |||
3694 | SourceRange R, bool receiverIdOrClass, | |||
3695 | SmallVectorImpl<ObjCMethodDecl*>& Methods); | |||
3696 | ||||
3697 | void | |||
3698 | DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, | |||
3699 | Selector Sel, SourceRange R, | |||
3700 | bool receiverIdOrClass); | |||
3701 | ||||
3702 | private: | |||
3703 | /// - Returns a selector which best matches given argument list or | |||
3704 | /// nullptr if none could be found | |||
3705 | ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, | |||
3706 | bool IsInstance, | |||
3707 | SmallVectorImpl<ObjCMethodDecl*>& Methods); | |||
3708 | ||||
3709 | ||||
3710 | /// Record the typo correction failure and return an empty correction. | |||
3711 | TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, | |||
3712 | bool RecordFailure = true) { | |||
3713 | if (RecordFailure) | |||
3714 | TypoCorrectionFailures[Typo].insert(TypoLoc); | |||
3715 | return TypoCorrection(); | |||
3716 | } | |||
3717 | ||||
3718 | public: | |||
3719 | /// AddInstanceMethodToGlobalPool - All instance methods in a translation | |||
3720 | /// unit are added to a global pool. This allows us to efficiently associate | |||
3721 | /// a selector with a method declaraation for purposes of typechecking | |||
3722 | /// messages sent to "id" (where the class of the object is unknown). | |||
3723 | void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { | |||
3724 | AddMethodToGlobalPool(Method, impl, /*instance*/true); | |||
3725 | } | |||
3726 | ||||
3727 | /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. | |||
3728 | void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { | |||
3729 | AddMethodToGlobalPool(Method, impl, /*instance*/false); | |||
3730 | } | |||
3731 | ||||
3732 | /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global | |||
3733 | /// pool. | |||
3734 | void AddAnyMethodToGlobalPool(Decl *D); | |||
3735 | ||||
3736 | /// LookupInstanceMethodInGlobalPool - Returns the method and warns if | |||
3737 | /// there are multiple signatures. | |||
3738 | ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, | |||
3739 | bool receiverIdOrClass=false) { | |||
3740 | return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, | |||
3741 | /*instance*/true); | |||
3742 | } | |||
3743 | ||||
3744 | /// LookupFactoryMethodInGlobalPool - Returns the method and warns if | |||
3745 | /// there are multiple signatures. | |||
3746 | ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, | |||
3747 | bool receiverIdOrClass=false) { | |||
3748 | return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, | |||
3749 | /*instance*/false); | |||
3750 | } | |||
3751 | ||||
3752 | const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, | |||
3753 | QualType ObjectType=QualType()); | |||
3754 | /// LookupImplementedMethodInGlobalPool - Returns the method which has an | |||
3755 | /// implementation. | |||
3756 | ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); | |||
3757 | ||||
3758 | /// CollectIvarsToConstructOrDestruct - Collect those ivars which require | |||
3759 | /// initialization. | |||
3760 | void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, | |||
3761 | SmallVectorImpl<ObjCIvarDecl*> &Ivars); | |||
3762 | ||||
3763 | //===--------------------------------------------------------------------===// | |||
3764 | // Statement Parsing Callbacks: SemaStmt.cpp. | |||
3765 | public: | |||
3766 | class FullExprArg { | |||
3767 | public: | |||
3768 | FullExprArg() : E(nullptr) { } | |||
3769 | FullExprArg(Sema &actions) : E(nullptr) { } | |||
3770 | ||||
3771 | ExprResult release() { | |||
3772 | return E; | |||
3773 | } | |||
3774 | ||||
3775 | Expr *get() const { return E; } | |||
3776 | ||||
3777 | Expr *operator->() { | |||
3778 | return E; | |||
3779 | } | |||
3780 | ||||
3781 | private: | |||
3782 | // FIXME: No need to make the entire Sema class a friend when it's just | |||
3783 | // Sema::MakeFullExpr that needs access to the constructor below. | |||
3784 | friend class Sema; | |||
3785 | ||||
3786 | explicit FullExprArg(Expr *expr) : E(expr) {} | |||
3787 | ||||
3788 | Expr *E; | |||
3789 | }; | |||
3790 | ||||
3791 | FullExprArg MakeFullExpr(Expr *Arg) { | |||
3792 | return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); | |||
3793 | } | |||
3794 | FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { | |||
3795 | return FullExprArg( | |||
3796 | ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); | |||
3797 | } | |||
3798 | FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { | |||
3799 | ExprResult FE = | |||
3800 | ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), | |||
3801 | /*DiscardedValue*/ true); | |||
3802 | return FullExprArg(FE.get()); | |||
3803 | } | |||
3804 | ||||
3805 | StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); | |||
3806 | StmtResult ActOnExprStmtError(); | |||
3807 | ||||
3808 | StmtResult ActOnNullStmt(SourceLocation SemiLoc, | |||
3809 | bool HasLeadingEmptyMacro = false); | |||
3810 | ||||
3811 | void ActOnStartOfCompoundStmt(bool IsStmtExpr); | |||
3812 | void ActOnFinishOfCompoundStmt(); | |||
3813 | StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, | |||
3814 | ArrayRef<Stmt *> Elts, bool isStmtExpr); | |||
3815 | ||||
3816 | /// A RAII object to enter scope of a compound statement. | |||
3817 | class CompoundScopeRAII { | |||
3818 | public: | |||
3819 | CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { | |||
3820 | S.ActOnStartOfCompoundStmt(IsStmtExpr); | |||
3821 | } | |||
3822 | ||||
3823 | ~CompoundScopeRAII() { | |||
3824 | S.ActOnFinishOfCompoundStmt(); | |||
3825 | } | |||
3826 | ||||
3827 | private: | |||
3828 | Sema &S; | |||
3829 | }; | |||
3830 | ||||
3831 | /// An RAII helper that pops function a function scope on exit. | |||
3832 | struct FunctionScopeRAII { | |||
3833 | Sema &S; | |||
3834 | bool Active; | |||
3835 | FunctionScopeRAII(Sema &S) : S(S), Active(true) {} | |||
3836 | ~FunctionScopeRAII() { | |||
3837 | if (Active) | |||
3838 | S.PopFunctionScopeInfo(); | |||
3839 | } | |||
3840 | void disable() { Active = false; } | |||
3841 | }; | |||
3842 | ||||
3843 | StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, | |||
3844 | SourceLocation StartLoc, | |||
3845 | SourceLocation EndLoc); | |||
3846 | void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); | |||
3847 | StmtResult ActOnForEachLValueExpr(Expr *E); | |||
3848 | ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); | |||
3849 | StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, | |||
3850 | SourceLocation DotDotDotLoc, ExprResult RHS, | |||
3851 | SourceLocation ColonLoc); | |||
3852 | void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); | |||
3853 | ||||
3854 | StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, | |||
3855 | SourceLocation ColonLoc, | |||
3856 | Stmt *SubStmt, Scope *CurScope); | |||
3857 | StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, | |||
3858 | SourceLocation ColonLoc, Stmt *SubStmt); | |||
3859 | ||||
3860 | StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, | |||
3861 | ArrayRef<const Attr*> Attrs, | |||
3862 | Stmt *SubStmt); | |||
3863 | ||||
3864 | class ConditionResult; | |||
3865 | StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, | |||
3866 | Stmt *InitStmt, | |||
3867 | ConditionResult Cond, Stmt *ThenVal, | |||
3868 | SourceLocation ElseLoc, Stmt *ElseVal); | |||
3869 | StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, | |||
3870 | Stmt *InitStmt, | |||
3871 | ConditionResult Cond, Stmt *ThenVal, | |||
3872 | SourceLocation ElseLoc, Stmt *ElseVal); | |||
3873 | StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, | |||
3874 | Stmt *InitStmt, | |||
3875 | ConditionResult Cond); | |||
3876 | StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, | |||
3877 | Stmt *Switch, Stmt *Body); | |||
3878 | StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, | |||
3879 | Stmt *Body); | |||
3880 | StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, | |||
3881 | SourceLocation WhileLoc, SourceLocation CondLParen, | |||
3882 | Expr *Cond, SourceLocation CondRParen); | |||
3883 | ||||
3884 | StmtResult ActOnForStmt(SourceLocation ForLoc, | |||
3885 | SourceLocation LParenLoc, | |||
3886 | Stmt *First, | |||
3887 | ConditionResult Second, | |||
3888 | FullExprArg Third, | |||
3889 | SourceLocation RParenLoc, | |||
3890 | Stmt *Body); | |||
3891 | ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, | |||
3892 | Expr *collection); | |||
3893 | StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, | |||
3894 | Stmt *First, Expr *collection, | |||
3895 | SourceLocation RParenLoc); | |||
3896 | StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); | |||
3897 | ||||
3898 | enum BuildForRangeKind { | |||
3899 | /// Initial building of a for-range statement. | |||
3900 | BFRK_Build, | |||
3901 | /// Instantiation or recovery rebuild of a for-range statement. Don't | |||
3902 | /// attempt any typo-correction. | |||
3903 | BFRK_Rebuild, | |||
3904 | /// Determining whether a for-range statement could be built. Avoid any | |||
3905 | /// unnecessary or irreversible actions. | |||
3906 | BFRK_Check | |||
3907 | }; | |||
3908 | ||||
3909 | StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, | |||
3910 | SourceLocation CoawaitLoc, | |||
3911 | Stmt *InitStmt, | |||
3912 | Stmt *LoopVar, | |||
3913 | SourceLocation ColonLoc, Expr *Collection, | |||
3914 | SourceLocation RParenLoc, | |||
3915 | BuildForRangeKind Kind); | |||
3916 | StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, | |||
3917 | SourceLocation CoawaitLoc, | |||
3918 | Stmt *InitStmt, | |||
3919 | SourceLocation ColonLoc, | |||
3920 | Stmt *RangeDecl, Stmt *Begin, Stmt *End, | |||
3921 | Expr *Cond, Expr *Inc, | |||
3922 | Stmt *LoopVarDecl, | |||
3923 | SourceLocation RParenLoc, | |||
3924 | BuildForRangeKind Kind); | |||
3925 | StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); | |||
3926 | ||||
3927 | StmtResult ActOnGotoStmt(SourceLocation GotoLoc, | |||
3928 | SourceLocation LabelLoc, | |||
3929 | LabelDecl *TheDecl); | |||
3930 | StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, | |||
3931 | SourceLocation StarLoc, | |||
3932 | Expr *DestExp); | |||
3933 | StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); | |||
3934 | StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); | |||
3935 | ||||
3936 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, | |||
3937 | CapturedRegionKind Kind, unsigned NumParams); | |||
3938 | typedef std::pair<StringRef, QualType> CapturedParamNameType; | |||
3939 | void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, | |||
3940 | CapturedRegionKind Kind, | |||
3941 | ArrayRef<CapturedParamNameType> Params); | |||
3942 | StmtResult ActOnCapturedRegionEnd(Stmt *S); | |||
3943 | void ActOnCapturedRegionError(); | |||
3944 | RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, | |||
3945 | SourceLocation Loc, | |||
3946 | unsigned NumParams); | |||
3947 | ||||
3948 | enum CopyElisionSemanticsKind { | |||
3949 | CES_Strict = 0, | |||
3950 | CES_AllowParameters = 1, | |||
3951 | CES_AllowDifferentTypes = 2, | |||
3952 | CES_AllowExceptionVariables = 4, | |||
3953 | CES_FormerDefault = (CES_AllowParameters), | |||
3954 | CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), | |||
3955 | CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | | |||
3956 | CES_AllowExceptionVariables), | |||
3957 | }; | |||
3958 | ||||
3959 | VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, | |||
3960 | CopyElisionSemanticsKind CESK); | |||
3961 | bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, | |||
3962 | CopyElisionSemanticsKind CESK); | |||
3963 | ||||
3964 | StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, | |||
3965 | Scope *CurScope); | |||
3966 | StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); | |||
3967 | StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); | |||
3968 | ||||
3969 | StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, | |||
3970 | bool IsVolatile, unsigned NumOutputs, | |||
3971 | unsigned NumInputs, IdentifierInfo **Names, | |||
3972 | MultiExprArg Constraints, MultiExprArg Exprs, | |||
3973 | Expr *AsmString, MultiExprArg Clobbers, | |||
3974 | SourceLocation RParenLoc); | |||
3975 | ||||
3976 | void FillInlineAsmIdentifierInfo(Expr *Res, | |||
3977 | llvm::InlineAsmIdentifierInfo &Info); | |||
3978 | ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, | |||
3979 | SourceLocation TemplateKWLoc, | |||
3980 | UnqualifiedId &Id, | |||
3981 | bool IsUnevaluatedContext); | |||
3982 | bool LookupInlineAsmField(StringRef Base, StringRef Member, | |||
3983 | unsigned &Offset, SourceLocation AsmLoc); | |||
3984 | ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, | |||
3985 | SourceLocation AsmLoc); | |||
3986 | StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, | |||
3987 | ArrayRef<Token> AsmToks, | |||
3988 | StringRef AsmString, | |||
3989 | unsigned NumOutputs, unsigned NumInputs, | |||
3990 | ArrayRef<StringRef> Constraints, | |||
3991 | ArrayRef<StringRef> Clobbers, | |||
3992 | ArrayRef<Expr*> Exprs, | |||
3993 | SourceLocation EndLoc); | |||
3994 | LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, | |||
3995 | SourceLocation Location, | |||
3996 | bool AlwaysCreate); | |||
3997 | ||||
3998 | VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, | |||
3999 | SourceLocation StartLoc, | |||
4000 | SourceLocation IdLoc, IdentifierInfo *Id, | |||
4001 | bool Invalid = false); | |||
4002 | ||||
4003 | Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); | |||
4004 | ||||
4005 | StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, | |||
4006 | Decl *Parm, Stmt *Body); | |||
4007 | ||||
4008 | StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); | |||
4009 | ||||
4010 | StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, | |||
4011 | MultiStmtArg Catch, Stmt *Finally); | |||
4012 | ||||
4013 | StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); | |||
4014 | StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, | |||
4015 | Scope *CurScope); | |||
4016 | ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, | |||
4017 | Expr *operand); | |||
4018 | StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, | |||
4019 | Expr *SynchExpr, | |||
4020 | Stmt *SynchBody); | |||
4021 | ||||
4022 | StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); | |||
4023 | ||||
4024 | VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, | |||
4025 | SourceLocation StartLoc, | |||
4026 | SourceLocation IdLoc, | |||
4027 | IdentifierInfo *Id); | |||
4028 | ||||
4029 | Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); | |||
4030 | ||||
4031 | StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, | |||
4032 | Decl *ExDecl, Stmt *HandlerBlock); | |||
4033 | StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, | |||
4034 | ArrayRef<Stmt *> Handlers); | |||
4035 | ||||
4036 | StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? | |||
4037 | SourceLocation TryLoc, Stmt *TryBlock, | |||
4038 | Stmt *Handler); | |||
4039 | StmtResult ActOnSEHExceptBlock(SourceLocation Loc, | |||
4040 | Expr *FilterExpr, | |||
4041 | Stmt *Block); | |||
4042 | void ActOnStartSEHFinallyBlock(); | |||
4043 | void ActOnAbortSEHFinallyBlock(); | |||
4044 | StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); | |||
4045 | StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); | |||
4046 | ||||
4047 | void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); | |||
4048 | ||||
4049 | bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; | |||
4050 | ||||
4051 | /// If it's a file scoped decl that must warn if not used, keep track | |||
4052 | /// of it. | |||
4053 | void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); | |||
4054 | ||||
4055 | /// DiagnoseUnusedExprResult - If the statement passed in is an expression | |||
4056 | /// whose result is unused, warn. | |||
4057 | void DiagnoseUnusedExprResult(const Stmt *S); | |||
4058 | void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); | |||
4059 | void DiagnoseUnusedDecl(const NamedDecl *ND); | |||
4060 | ||||
4061 | /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null | |||
4062 | /// statement as a \p Body, and it is located on the same line. | |||
4063 | /// | |||
4064 | /// This helps prevent bugs due to typos, such as: | |||
4065 | /// if (condition); | |||
4066 | /// do_stuff(); | |||
4067 | void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, | |||
4068 | const Stmt *Body, | |||
4069 | unsigned DiagID); | |||
4070 | ||||
4071 | /// Warn if a for/while loop statement \p S, which is followed by | |||
4072 | /// \p PossibleBody, has a suspicious null statement as a body. | |||
4073 | void DiagnoseEmptyLoopBody(const Stmt *S, | |||
4074 | const Stmt *PossibleBody); | |||
4075 | ||||
4076 | /// Warn if a value is moved to itself. | |||
4077 | void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, | |||
4078 | SourceLocation OpLoc); | |||
4079 | ||||
4080 | /// Warn if we're implicitly casting from a _Nullable pointer type to a | |||
4081 | /// _Nonnull one. | |||
4082 | void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, | |||
4083 | SourceLocation Loc); | |||
4084 | ||||
4085 | /// Warn when implicitly casting 0 to nullptr. | |||
4086 | void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); | |||
4087 | ||||
4088 | ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { | |||
4089 | return DelayedDiagnostics.push(pool); | |||
4090 | } | |||
4091 | void PopParsingDeclaration(ParsingDeclState state, Decl *decl); | |||
4092 | ||||
4093 | typedef ProcessingContextState ParsingClassState; | |||
4094 | ParsingClassState PushParsingClass() { | |||
4095 | return DelayedDiagnostics.pushUndelayed(); | |||
4096 | } | |||
4097 | void PopParsingClass(ParsingClassState state) { | |||
4098 | DelayedDiagnostics.popUndelayed(state); | |||
4099 | } | |||
4100 | ||||
4101 | void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); | |||
4102 | ||||
4103 | void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | |||
4104 | const ObjCInterfaceDecl *UnknownObjCClass, | |||
4105 | bool ObjCPropertyAccess, | |||
4106 | bool AvoidPartialAvailabilityChecks = false, | |||
4107 | ObjCInterfaceDecl *ClassReceiver = nullptr); | |||
4108 | ||||
4109 | bool makeUnavailableInSystemHeader(SourceLocation loc, | |||
4110 | UnavailableAttr::ImplicitReason reason); | |||
4111 | ||||
4112 | /// Issue any -Wunguarded-availability warnings in \c FD | |||
4113 | void DiagnoseUnguardedAvailabilityViolations(Decl *FD); | |||
4114 | ||||
4115 | //===--------------------------------------------------------------------===// | |||
4116 | // Expression Parsing Callbacks: SemaExpr.cpp. | |||
4117 | ||||
4118 | bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); | |||
4119 | bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, | |||
4120 | const ObjCInterfaceDecl *UnknownObjCClass = nullptr, | |||
4121 | bool ObjCPropertyAccess = false, | |||
4122 | bool AvoidPartialAvailabilityChecks = false, | |||
4123 | ObjCInterfaceDecl *ClassReciever = nullptr); | |||
4124 | void NoteDeletedFunction(FunctionDecl *FD); | |||
4125 | void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); | |||
4126 | bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, | |||
4127 | ObjCMethodDecl *Getter, | |||
4128 | SourceLocation Loc); | |||
4129 | void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, | |||
4130 | ArrayRef<Expr *> Args); | |||
4131 | ||||
4132 | void PushExpressionEvaluationContext( | |||
4133 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, | |||
4134 | ExpressionEvaluationContextRecord::ExpressionKind Type = | |||
4135 | ExpressionEvaluationContextRecord::EK_Other); | |||
4136 | enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; | |||
4137 | void PushExpressionEvaluationContext( | |||
4138 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, | |||
4139 | ExpressionEvaluationContextRecord::ExpressionKind Type = | |||
4140 | ExpressionEvaluationContextRecord::EK_Other); | |||
4141 | void PopExpressionEvaluationContext(); | |||
4142 | ||||
4143 | void DiscardCleanupsInEvaluationContext(); | |||
4144 | ||||
4145 | ExprResult TransformToPotentiallyEvaluated(Expr *E); | |||
4146 | ExprResult HandleExprEvaluationContextForTypeof(Expr *E); | |||
4147 | ||||
4148 | ExprResult ActOnConstantExpression(ExprResult Res); | |||
4149 | ||||
4150 | // Functions for marking a declaration referenced. These functions also | |||
4151 | // contain the relevant logic for marking if a reference to a function or | |||
4152 | // variable is an odr-use (in the C++11 sense). There are separate variants | |||
4153 | // for expressions referring to a decl; these exist because odr-use marking | |||
4154 | // needs to be delayed for some constant variables when we build one of the | |||
4155 | // named expressions. | |||
4156 | // | |||
4157 | // MightBeOdrUse indicates whether the use could possibly be an odr-use, and | |||
4158 | // should usually be true. This only needs to be set to false if the lack of | |||
4159 | // odr-use cannot be determined from the current context (for instance, | |||
4160 | // because the name denotes a virtual function and was written without an | |||
4161 | // explicit nested-name-specifier). | |||
4162 | void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); | |||
4163 | void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, | |||
4164 | bool MightBeOdrUse = true); | |||
4165 | void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); | |||
4166 | void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); | |||
4167 | void MarkMemberReferenced(MemberExpr *E); | |||
4168 | ||||
4169 | void UpdateMarkingForLValueToRValue(Expr *E); | |||
4170 | void CleanupVarDeclMarking(); | |||
4171 | ||||
4172 | enum TryCaptureKind { | |||
4173 | TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef | |||
4174 | }; | |||
4175 | ||||
4176 | /// Try to capture the given variable. | |||
4177 | /// | |||
4178 | /// \param Var The variable to capture. | |||
4179 | /// | |||
4180 | /// \param Loc The location at which the capture occurs. | |||
4181 | /// | |||
4182 | /// \param Kind The kind of capture, which may be implicit (for either a | |||
4183 | /// block or a lambda), or explicit by-value or by-reference (for a lambda). | |||
4184 | /// | |||
4185 | /// \param EllipsisLoc The location of the ellipsis, if one is provided in | |||
4186 | /// an explicit lambda capture. | |||
4187 | /// | |||
4188 | /// \param BuildAndDiagnose Whether we are actually supposed to add the | |||
4189 | /// captures or diagnose errors. If false, this routine merely check whether | |||
4190 | /// the capture can occur without performing the capture itself or complaining | |||
4191 | /// if the variable cannot be captured. | |||
4192 | /// | |||
4193 | /// \param CaptureType Will be set to the type of the field used to capture | |||
4194 | /// this variable in the innermost block or lambda. Only valid when the | |||
4195 | /// variable can be captured. | |||
4196 | /// | |||
4197 | /// \param DeclRefType Will be set to the type of a reference to the capture | |||
4198 | /// from within the current scope. Only valid when the variable can be | |||
4199 | /// captured. | |||
4200 | /// | |||
4201 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index | |||
4202 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. | |||
4203 | /// This is useful when enclosing lambdas must speculatively capture | |||
4204 | /// variables that may or may not be used in certain specializations of | |||
4205 | /// a nested generic lambda. | |||
4206 | /// | |||
4207 | /// \returns true if an error occurred (i.e., the variable cannot be | |||
4208 | /// captured) and false if the capture succeeded. | |||
4209 | bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, | |||
4210 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, | |||
4211 | QualType &CaptureType, | |||
4212 | QualType &DeclRefType, | |||
4213 | const unsigned *const FunctionScopeIndexToStopAt); | |||
4214 | ||||
4215 | /// Try to capture the given variable. | |||
4216 | bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, | |||
4217 | TryCaptureKind Kind = TryCapture_Implicit, | |||
4218 | SourceLocation EllipsisLoc = SourceLocation()); | |||
4219 | ||||
4220 | /// Checks if the variable must be captured. | |||
4221 | bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); | |||
4222 | ||||
4223 | /// Given a variable, determine the type that a reference to that | |||
4224 | /// variable will have in the given scope. | |||
4225 | QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); | |||
4226 | ||||
4227 | /// Mark all of the declarations referenced within a particular AST node as | |||
4228 | /// referenced. Used when template instantiation instantiates a non-dependent | |||
4229 | /// type -- entities referenced by the type are now referenced. | |||
4230 | void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); | |||
4231 | void MarkDeclarationsReferencedInExpr(Expr *E, | |||
4232 | bool SkipLocalVariables = false); | |||
4233 | ||||
4234 | /// Try to recover by turning the given expression into a | |||
4235 | /// call. Returns true if recovery was attempted or an error was | |||
4236 | /// emitted; this may also leave the ExprResult invalid. | |||
4237 | bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, | |||
4238 | bool ForceComplain = false, | |||
4239 | bool (*IsPlausibleResult)(QualType) = nullptr); | |||
4240 | ||||
4241 | /// Figure out if an expression could be turned into a call. | |||
4242 | bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, | |||
4243 | UnresolvedSetImpl &NonTemplateOverloads); | |||
4244 | ||||
4245 | /// Conditionally issue a diagnostic based on the current | |||
4246 | /// evaluation context. | |||
4247 | /// | |||
4248 | /// \param Statement If Statement is non-null, delay reporting the | |||
4249 | /// diagnostic until the function body is parsed, and then do a basic | |||
4250 | /// reachability analysis to determine if the statement is reachable. | |||
4251 | /// If it is unreachable, the diagnostic will not be emitted. | |||
4252 | bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, | |||
4253 | const PartialDiagnostic &PD); | |||
4254 | /// Similar, but diagnostic is only produced if all the specified statements | |||
4255 | /// are reachable. | |||
4256 | bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, | |||
4257 | const PartialDiagnostic &PD); | |||
4258 | ||||
4259 | // Primary Expressions. | |||
4260 | SourceRange getExprRange(Expr *E) const; | |||
4261 | ||||
4262 | ExprResult ActOnIdExpression( | |||
4263 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, | |||
4264 | UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, | |||
4265 | CorrectionCandidateCallback *CCC = nullptr, | |||
4266 | bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); | |||
4267 | ||||
4268 | void DecomposeUnqualifiedId(const UnqualifiedId &Id, | |||
4269 | TemplateArgumentListInfo &Buffer, | |||
4270 | DeclarationNameInfo &NameInfo, | |||
4271 | const TemplateArgumentListInfo *&TemplateArgs); | |||
4272 | ||||
4273 | bool | |||
4274 | DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, | |||
4275 | CorrectionCandidateCallback &CCC, | |||
4276 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, | |||
4277 | ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); | |||
4278 | ||||
4279 | ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, | |||
4280 | IdentifierInfo *II, | |||
4281 | bool AllowBuiltinCreation=false); | |||
4282 | ||||
4283 | ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, | |||
4284 | SourceLocation TemplateKWLoc, | |||
4285 | const DeclarationNameInfo &NameInfo, | |||
4286 | bool isAddressOfOperand, | |||
4287 | const TemplateArgumentListInfo *TemplateArgs); | |||
4288 | ||||
4289 | ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, | |||
4290 | ExprValueKind VK, | |||
4291 | SourceLocation Loc, | |||
4292 | const CXXScopeSpec *SS = nullptr); | |||
4293 | ExprResult | |||
4294 | BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, | |||
4295 | const DeclarationNameInfo &NameInfo, | |||
4296 | const CXXScopeSpec *SS = nullptr, | |||
4297 | NamedDecl *FoundD = nullptr, | |||
4298 | const TemplateArgumentListInfo *TemplateArgs = nullptr); | |||
4299 | ExprResult | |||
4300 | BuildAnonymousStructUnionMemberReference( | |||
4301 | const CXXScopeSpec &SS, | |||
4302 | SourceLocation nameLoc, | |||
4303 | IndirectFieldDecl *indirectField, | |||
4304 | DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), | |||
4305 | Expr *baseObjectExpr = nullptr, | |||
4306 | SourceLocation opLoc = SourceLocation()); | |||
4307 | ||||
4308 | ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, | |||
4309 | SourceLocation TemplateKWLoc, | |||
4310 | LookupResult &R, | |||
4311 | const TemplateArgumentListInfo *TemplateArgs, | |||
4312 | const Scope *S); | |||
4313 | ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, | |||
4314 | SourceLocation TemplateKWLoc, | |||
4315 | LookupResult &R, | |||
4316 | const TemplateArgumentListInfo *TemplateArgs, | |||
4317 | bool IsDefiniteInstance, | |||
4318 | const Scope *S); | |||
4319 | bool UseArgumentDependentLookup(const CXXScopeSpec &SS, | |||
4320 | const LookupResult &R, | |||
4321 | bool HasTrailingLParen); | |||
4322 | ||||
4323 | ExprResult | |||
4324 | BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, | |||
4325 | const DeclarationNameInfo &NameInfo, | |||
4326 | bool IsAddressOfOperand, const Scope *S, | |||
4327 | TypeSourceInfo **RecoveryTSI = nullptr); | |||
4328 | ||||
4329 | ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, | |||
4330 | SourceLocation TemplateKWLoc, | |||
4331 | const DeclarationNameInfo &NameInfo, | |||
4332 | const TemplateArgumentListInfo *TemplateArgs); | |||
4333 | ||||
4334 | ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, | |||
4335 | LookupResult &R, | |||
4336 | bool NeedsADL, | |||
4337 | bool AcceptInvalidDecl = false); | |||
4338 | ExprResult BuildDeclarationNameExpr( | |||
4339 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, | |||
4340 | NamedDecl *FoundD = nullptr, | |||
4341 | const TemplateArgumentListInfo *TemplateArgs = nullptr, | |||
4342 | bool AcceptInvalidDecl = false); | |||
4343 | ||||
4344 | ExprResult BuildLiteralOperatorCall(LookupResult &R, | |||
4345 | DeclarationNameInfo &SuffixInfo, | |||
4346 | ArrayRef<Expr *> Args, | |||
4347 | SourceLocation LitEndLoc, | |||
4348 | TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); | |||
4349 | ||||
4350 | ExprResult BuildPredefinedExpr(SourceLocation Loc, | |||
4351 | PredefinedExpr::IdentKind IK); | |||
4352 | ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); | |||
4353 | ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); | |||
4354 | ||||
4355 | bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); | |||
4356 | ||||
4357 | ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); | |||
4358 | ExprResult ActOnCharacterConstant(const Token &Tok, | |||
4359 | Scope *UDLScope = nullptr); | |||
4360 | ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); | |||
4361 | ExprResult ActOnParenListExpr(SourceLocation L, | |||
4362 | SourceLocation R, | |||
4363 | MultiExprArg Val); | |||
4364 | ||||
4365 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string | |||
4366 | /// fragments (e.g. "foo" "bar" L"baz"). | |||
4367 | ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, | |||
4368 | Scope *UDLScope = nullptr); | |||
4369 | ||||
4370 | ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, | |||
4371 | SourceLocation DefaultLoc, | |||
4372 | SourceLocation RParenLoc, | |||
4373 | Expr *ControllingExpr, | |||
4374 | ArrayRef<ParsedType> ArgTypes, | |||
4375 | ArrayRef<Expr *> ArgExprs); | |||
4376 | ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, | |||
4377 | SourceLocation DefaultLoc, | |||
4378 | SourceLocation RParenLoc, | |||
4379 | Expr *ControllingExpr, | |||
4380 | ArrayRef<TypeSourceInfo *> Types, | |||
4381 | ArrayRef<Expr *> Exprs); | |||
4382 | ||||
4383 | // Binary/Unary Operators. 'Tok' is the token for the operator. | |||
4384 | ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, | |||
4385 | Expr *InputExpr); | |||
4386 | ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, | |||
4387 | UnaryOperatorKind Opc, Expr *Input); | |||
4388 | ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, | |||
4389 | tok::TokenKind Op, Expr *Input); | |||
4390 | ||||
4391 | bool isQualifiedMemberAccess(Expr *E); | |||
4392 | QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); | |||
4393 | ||||
4394 | ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, | |||
4395 | SourceLocation OpLoc, | |||
4396 | UnaryExprOrTypeTrait ExprKind, | |||
4397 | SourceRange R); | |||
4398 | ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, | |||
4399 | UnaryExprOrTypeTrait ExprKind); | |||
4400 | ExprResult | |||
4401 | ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, | |||
4402 | UnaryExprOrTypeTrait ExprKind, | |||
4403 | bool IsType, void *TyOrEx, | |||
4404 | SourceRange ArgRange); | |||
4405 | ||||
4406 | ExprResult CheckPlaceholderExpr(Expr *E); | |||
4407 | bool CheckVecStepExpr(Expr *E); | |||
4408 | ||||
4409 | bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); | |||
4410 | bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, | |||
4411 | SourceRange ExprRange, | |||
4412 | UnaryExprOrTypeTrait ExprKind); | |||
4413 | ExprResult ActOnSizeofParameterPackExpr(Scope *S, | |||
4414 | SourceLocation OpLoc, | |||
4415 | IdentifierInfo &Name, | |||
4416 | SourceLocation NameLoc, | |||
4417 | SourceLocation RParenLoc); | |||
4418 | ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, | |||
4419 | tok::TokenKind Kind, Expr *Input); | |||
4420 | ||||
4421 | ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, | |||
4422 | Expr *Idx, SourceLocation RLoc); | |||
4423 | ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, | |||
4424 | Expr *Idx, SourceLocation RLoc); | |||
4425 | ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, | |||
4426 | Expr *LowerBound, SourceLocation ColonLoc, | |||
4427 | Expr *Length, SourceLocation RBLoc); | |||
4428 | ||||
4429 | // This struct is for use by ActOnMemberAccess to allow | |||
4430 | // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after | |||
4431 | // changing the access operator from a '.' to a '->' (to see if that is the | |||
4432 | // change needed to fix an error about an unknown member, e.g. when the class | |||
4433 | // defines a custom operator->). | |||
4434 | struct ActOnMemberAccessExtraArgs { | |||
4435 | Scope *S; | |||
4436 | UnqualifiedId &Id; | |||
4437 | Decl *ObjCImpDecl; | |||
4438 | }; | |||
4439 | ||||
4440 | ExprResult BuildMemberReferenceExpr( | |||
4441 | Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, | |||
4442 | CXXScopeSpec &SS, SourceLocation TemplateKWLoc, | |||
4443 | NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, | |||
4444 | const TemplateArgumentListInfo *TemplateArgs, | |||
4445 | const Scope *S, | |||
4446 | ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); | |||
4447 | ||||
4448 | ExprResult | |||
4449 | BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, | |||
4450 | bool IsArrow, const CXXScopeSpec &SS, | |||
4451 | SourceLocation TemplateKWLoc, | |||
4452 | NamedDecl *FirstQualifierInScope, LookupResult &R, | |||
4453 | const TemplateArgumentListInfo *TemplateArgs, | |||
4454 | const Scope *S, | |||
4455 | bool SuppressQualifierCheck = false, | |||
4456 | ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); | |||
4457 | ||||
4458 | ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, | |||
4459 | SourceLocation OpLoc, | |||
4460 | const CXXScopeSpec &SS, FieldDecl *Field, | |||
4461 | DeclAccessPair FoundDecl, | |||
4462 | const DeclarationNameInfo &MemberNameInfo); | |||
4463 | ||||
4464 | ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); | |||
4465 | ||||
4466 | bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, | |||
4467 | const CXXScopeSpec &SS, | |||
4468 | const LookupResult &R); | |||
4469 | ||||
4470 | ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, | |||
4471 | bool IsArrow, SourceLocation OpLoc, | |||
4472 | const CXXScopeSpec &SS, | |||
4473 | SourceLocation TemplateKWLoc, | |||
4474 | NamedDecl *FirstQualifierInScope, | |||
4475 | const DeclarationNameInfo &NameInfo, | |||
4476 | const TemplateArgumentListInfo *TemplateArgs); | |||
4477 | ||||
4478 | ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, | |||
4479 | SourceLocation OpLoc, | |||
4480 | tok::TokenKind OpKind, | |||
4481 | CXXScopeSpec &SS, | |||
4482 | SourceLocation TemplateKWLoc, | |||
4483 | UnqualifiedId &Member, | |||
4484 | Decl *ObjCImpDecl); | |||
4485 | ||||
4486 | void ActOnDefaultCtorInitializers(Decl *CDtorDecl); | |||
4487 | bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, | |||
4488 | FunctionDecl *FDecl, | |||
4489 | const FunctionProtoType *Proto, | |||
4490 | ArrayRef<Expr *> Args, | |||
4491 | SourceLocation RParenLoc, | |||
4492 | bool ExecConfig = false); | |||
4493 | void CheckStaticArrayArgument(SourceLocation CallLoc, | |||
4494 | ParmVarDecl *Param, | |||
4495 | const Expr *ArgExpr); | |||
4496 | ||||
4497 | /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. | |||
4498 | /// This provides the location of the left/right parens and a list of comma | |||
4499 | /// locations. | |||
4500 | ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, | |||
4501 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
4502 | Expr *ExecConfig = nullptr); | |||
4503 | ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, | |||
4504 | MultiExprArg ArgExprs, SourceLocation RParenLoc, | |||
4505 | Expr *ExecConfig = nullptr, | |||
4506 | bool IsExecConfig = false); | |||
4507 | ExprResult | |||
4508 | BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, | |||
4509 | ArrayRef<Expr *> Arg, SourceLocation RParenLoc, | |||
4510 | Expr *Config = nullptr, bool IsExecConfig = false, | |||
4511 | ADLCallKind UsesADL = ADLCallKind::NotADL); | |||
4512 | ||||
4513 | ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, | |||
4514 | MultiExprArg ExecConfig, | |||
4515 | SourceLocation GGGLoc); | |||
4516 | ||||
4517 | ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, | |||
4518 | Declarator &D, ParsedType &Ty, | |||
4519 | SourceLocation RParenLoc, Expr *CastExpr); | |||
4520 | ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, | |||
4521 | TypeSourceInfo *Ty, | |||
4522 | SourceLocation RParenLoc, | |||
4523 | Expr *Op); | |||
4524 | CastKind PrepareScalarCast(ExprResult &src, QualType destType); | |||
4525 | ||||
4526 | /// Build an altivec or OpenCL literal. | |||
4527 | ExprResult BuildVectorLiteral(SourceLocation LParenLoc, | |||
4528 | SourceLocation RParenLoc, Expr *E, | |||
4529 | TypeSourceInfo *TInfo); | |||
4530 | ||||
4531 | ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); | |||
4532 | ||||
4533 | ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, | |||
4534 | ParsedType Ty, | |||
4535 | SourceLocation RParenLoc, | |||
4536 | Expr *InitExpr); | |||
4537 | ||||
4538 | ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, | |||
4539 | TypeSourceInfo *TInfo, | |||
4540 | SourceLocation RParenLoc, | |||
4541 | Expr *LiteralExpr); | |||
4542 | ||||
4543 | ExprResult ActOnInitList(SourceLocation LBraceLoc, | |||
4544 | MultiExprArg InitArgList, | |||
4545 | SourceLocation RBraceLoc); | |||
4546 | ||||
4547 | ExprResult ActOnDesignatedInitializer(Designation &Desig, | |||
4548 | SourceLocation Loc, | |||
4549 | bool GNUSyntax, | |||
4550 | ExprResult Init); | |||
4551 | ||||
4552 | private: | |||
4553 | static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); | |||
4554 | ||||
4555 | public: | |||
4556 | ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, | |||
4557 | tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); | |||
4558 | ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, | |||
4559 | BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); | |||
4560 | ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, | |||
4561 | Expr *LHSExpr, Expr *RHSExpr); | |||
4562 | ||||
4563 | void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); | |||
4564 | ||||
4565 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null | |||
4566 | /// in the case of a the GNU conditional expr extension. | |||
4567 | ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, | |||
4568 | SourceLocation ColonLoc, | |||
4569 | Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); | |||
4570 | ||||
4571 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". | |||
4572 | ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, | |||
4573 | LabelDecl *TheDecl); | |||
4574 | ||||
4575 | void ActOnStartStmtExpr(); | |||
4576 | ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, | |||
4577 | SourceLocation RPLoc); // "({..})" | |||
4578 | // Handle the final expression in a statement expression. | |||
4579 | ExprResult ActOnStmtExprResult(ExprResult E); | |||
4580 | void ActOnStmtExprError(); | |||
4581 | ||||
4582 | // __builtin_offsetof(type, identifier(.identifier|[expr])*) | |||
4583 | struct OffsetOfComponent { | |||
4584 | SourceLocation LocStart, LocEnd; | |||
4585 | bool isBrackets; // true if [expr], false if .ident | |||
4586 | union { | |||
4587 | IdentifierInfo *IdentInfo; | |||
4588 | Expr *E; | |||
4589 | } U; | |||
4590 | }; | |||
4591 | ||||
4592 | /// __builtin_offsetof(type, a.b[123][456].c) | |||
4593 | ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, | |||
4594 | TypeSourceInfo *TInfo, | |||
4595 | ArrayRef<OffsetOfComponent> Components, | |||
4596 | SourceLocation RParenLoc); | |||
4597 | ExprResult ActOnBuiltinOffsetOf(Scope *S, | |||
4598 | SourceLocation BuiltinLoc, | |||
4599 | SourceLocation TypeLoc, | |||
4600 | ParsedType ParsedArgTy, | |||
4601 | ArrayRef<OffsetOfComponent> Components, | |||
4602 | SourceLocation RParenLoc); | |||
4603 | ||||
4604 | // __builtin_choose_expr(constExpr, expr1, expr2) | |||
4605 | ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, | |||
4606 | Expr *CondExpr, Expr *LHSExpr, | |||
4607 | Expr *RHSExpr, SourceLocation RPLoc); | |||
4608 | ||||
4609 | // __builtin_va_arg(expr, type) | |||
4610 | ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, | |||
4611 | SourceLocation RPLoc); | |||
4612 | ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, | |||
4613 | TypeSourceInfo *TInfo, SourceLocation RPLoc); | |||
4614 | ||||
4615 | // __null | |||
4616 | ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); | |||
4617 | ||||
4618 | bool CheckCaseExpression(Expr *E); | |||
4619 | ||||
4620 | /// Describes the result of an "if-exists" condition check. | |||
4621 | enum IfExistsResult { | |||
4622 | /// The symbol exists. | |||
4623 | IER_Exists, | |||
4624 | ||||
4625 | /// The symbol does not exist. | |||
4626 | IER_DoesNotExist, | |||
4627 | ||||
4628 | /// The name is a dependent name, so the results will differ | |||
4629 | /// from one instantiation to the next. | |||
4630 | IER_Dependent, | |||
4631 | ||||
4632 | /// An error occurred. | |||
4633 | IER_Error | |||
4634 | }; | |||
4635 | ||||
4636 | IfExistsResult | |||
4637 | CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, | |||
4638 | const DeclarationNameInfo &TargetNameInfo); | |||
4639 | ||||
4640 | IfExistsResult | |||
4641 | CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, | |||
4642 | bool IsIfExists, CXXScopeSpec &SS, | |||
4643 | UnqualifiedId &Name); | |||
4644 | ||||
4645 | StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, | |||
4646 | bool IsIfExists, | |||
4647 | NestedNameSpecifierLoc QualifierLoc, | |||
4648 | DeclarationNameInfo NameInfo, | |||
4649 | Stmt *Nested); | |||
4650 | StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, | |||
4651 | bool IsIfExists, | |||
4652 | CXXScopeSpec &SS, UnqualifiedId &Name, | |||
4653 | Stmt *Nested); | |||
4654 | ||||
4655 | //===------------------------- "Block" Extension ------------------------===// | |||
4656 | ||||
4657 | /// ActOnBlockStart - This callback is invoked when a block literal is | |||
4658 | /// started. | |||
4659 | void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); | |||
4660 | ||||
4661 | /// ActOnBlockArguments - This callback allows processing of block arguments. | |||
4662 | /// If there are no arguments, this is still invoked. | |||
4663 | void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, | |||
4664 | Scope *CurScope); | |||
4665 | ||||
4666 | /// ActOnBlockError - If there is an error parsing a block, this callback | |||
4667 | /// is invoked to pop the information about the block from the action impl. | |||
4668 | void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); | |||
4669 | ||||
4670 | /// ActOnBlockStmtExpr - This is called when the body of a block statement | |||
4671 | /// literal was successfully completed. ^(int x){...} | |||
4672 | ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, | |||
4673 | Scope *CurScope); | |||
4674 | ||||
4675 | //===---------------------------- Clang Extensions ----------------------===// | |||
4676 | ||||
4677 | /// __builtin_convertvector(...) | |||
4678 | ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, | |||
4679 | SourceLocation BuiltinLoc, | |||
4680 | SourceLocation RParenLoc); | |||
4681 | ||||
4682 | //===---------------------------- OpenCL Features -----------------------===// | |||
4683 | ||||
4684 | /// __builtin_astype(...) | |||
4685 | ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, | |||
4686 | SourceLocation BuiltinLoc, | |||
4687 | SourceLocation RParenLoc); | |||
4688 | ||||
4689 | //===---------------------------- C++ Features --------------------------===// | |||
4690 | ||||
4691 | // Act on C++ namespaces | |||
4692 | Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, | |||
4693 | SourceLocation NamespaceLoc, | |||
4694 | SourceLocation IdentLoc, IdentifierInfo *Ident, | |||
4695 | SourceLocation LBrace, | |||
4696 | const ParsedAttributesView &AttrList, | |||
4697 | UsingDirectiveDecl *&UsingDecl); | |||
4698 | void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); | |||
4699 | ||||
4700 | NamespaceDecl *getStdNamespace() const; | |||
4701 | NamespaceDecl *getOrCreateStdNamespace(); | |||
4702 | ||||
4703 | NamespaceDecl *lookupStdExperimentalNamespace(); | |||
4704 | ||||
4705 | CXXRecordDecl *getStdBadAlloc() const; | |||
4706 | EnumDecl *getStdAlignValT() const; | |||
4707 | ||||
4708 | private: | |||
4709 | // A cache representing if we've fully checked the various comparison category | |||
4710 | // types stored in ASTContext. The bit-index corresponds to the integer value | |||
4711 | // of a ComparisonCategoryType enumerator. | |||
4712 | llvm::SmallBitVector FullyCheckedComparisonCategories; | |||
4713 | ||||
4714 | ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, | |||
4715 | CXXScopeSpec &SS, | |||
4716 | ParsedType TemplateTypeTy, | |||
4717 | IdentifierInfo *MemberOrBase); | |||
4718 | ||||
4719 | public: | |||
4720 | /// Lookup the specified comparison category types in the standard | |||
4721 | /// library, an check the VarDecls possibly returned by the operator<=> | |||
4722 | /// builtins for that type. | |||
4723 | /// | |||
4724 | /// \return The type of the comparison category type corresponding to the | |||
4725 | /// specified Kind, or a null type if an error occurs | |||
4726 | QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, | |||
4727 | SourceLocation Loc); | |||
4728 | ||||
4729 | /// Tests whether Ty is an instance of std::initializer_list and, if | |||
4730 | /// it is and Element is not NULL, assigns the element type to Element. | |||
4731 | bool isStdInitializerList(QualType Ty, QualType *Element); | |||
4732 | ||||
4733 | /// Looks for the std::initializer_list template and instantiates it | |||
4734 | /// with Element, or emits an error if it's not found. | |||
4735 | /// | |||
4736 | /// \returns The instantiated template, or null on error. | |||
4737 | QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); | |||
4738 | ||||
4739 | /// Determine whether Ctor is an initializer-list constructor, as | |||
4740 | /// defined in [dcl.init.list]p2. | |||
4741 | bool isInitListConstructor(const FunctionDecl *Ctor); | |||
4742 | ||||
4743 | Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, | |||
4744 | SourceLocation NamespcLoc, CXXScopeSpec &SS, | |||
4745 | SourceLocation IdentLoc, | |||
4746 | IdentifierInfo *NamespcName, | |||
4747 | const ParsedAttributesView &AttrList); | |||
4748 | ||||
4749 | void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); | |||
4750 | ||||
4751 | Decl *ActOnNamespaceAliasDef(Scope *CurScope, | |||
4752 | SourceLocation NamespaceLoc, | |||
4753 | SourceLocation AliasLoc, | |||
4754 | IdentifierInfo *Alias, | |||
4755 | CXXScopeSpec &SS, | |||
4756 | SourceLocation IdentLoc, | |||
4757 | IdentifierInfo *Ident); | |||
4758 | ||||
4759 | void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); | |||
4760 | bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, | |||
4761 | const LookupResult &PreviousDecls, | |||
4762 | UsingShadowDecl *&PrevShadow); | |||
4763 | UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, | |||
4764 | NamedDecl *Target, | |||
4765 | UsingShadowDecl *PrevDecl); | |||
4766 | ||||
4767 | bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, | |||
4768 | bool HasTypenameKeyword, | |||
4769 | const CXXScopeSpec &SS, | |||
4770 | SourceLocation NameLoc, | |||
4771 | const LookupResult &Previous); | |||
4772 | bool CheckUsingDeclQualifier(SourceLocation UsingLoc, | |||
4773 | bool HasTypename, | |||
4774 | const CXXScopeSpec &SS, | |||
4775 | const DeclarationNameInfo &NameInfo, | |||
4776 | SourceLocation NameLoc); | |||
4777 | ||||
4778 | NamedDecl *BuildUsingDeclaration( | |||
4779 | Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, | |||
4780 | bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, | |||
4781 | DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, | |||
4782 | const ParsedAttributesView &AttrList, bool IsInstantiation); | |||
4783 | NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, | |||
4784 | ArrayRef<NamedDecl *> Expansions); | |||
4785 | ||||
4786 | bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); | |||
4787 | ||||
4788 | /// Given a derived-class using shadow declaration for a constructor and the | |||
4789 | /// correspnding base class constructor, find or create the implicit | |||
4790 | /// synthesized derived class constructor to use for this initialization. | |||
4791 | CXXConstructorDecl * | |||
4792 | findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, | |||
4793 | ConstructorUsingShadowDecl *DerivedShadow); | |||
4794 | ||||
4795 | Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, | |||
4796 | SourceLocation UsingLoc, | |||
4797 | SourceLocation TypenameLoc, CXXScopeSpec &SS, | |||
4798 | UnqualifiedId &Name, SourceLocation EllipsisLoc, | |||
4799 | const ParsedAttributesView &AttrList); | |||
4800 | Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, | |||
4801 | MultiTemplateParamsArg TemplateParams, | |||
4802 | SourceLocation UsingLoc, UnqualifiedId &Name, | |||
4803 | const ParsedAttributesView &AttrList, | |||
4804 | TypeResult Type, Decl *DeclFromDeclSpec); | |||
4805 | ||||
4806 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, | |||
4807 | /// including handling of its default argument expressions. | |||
4808 | /// | |||
4809 | /// \param ConstructKind - a CXXConstructExpr::ConstructionKind | |||
4810 | ExprResult | |||
4811 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
4812 | NamedDecl *FoundDecl, | |||
4813 | CXXConstructorDecl *Constructor, MultiExprArg Exprs, | |||
4814 | bool HadMultipleCandidates, bool IsListInitialization, | |||
4815 | bool IsStdInitListInitialization, | |||
4816 | bool RequiresZeroInit, unsigned ConstructKind, | |||
4817 | SourceRange ParenRange); | |||
4818 | ||||
4819 | /// Build a CXXConstructExpr whose constructor has already been resolved if | |||
4820 | /// it denotes an inherited constructor. | |||
4821 | ExprResult | |||
4822 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
4823 | CXXConstructorDecl *Constructor, bool Elidable, | |||
4824 | MultiExprArg Exprs, | |||
4825 | bool HadMultipleCandidates, bool IsListInitialization, | |||
4826 | bool IsStdInitListInitialization, | |||
4827 | bool RequiresZeroInit, unsigned ConstructKind, | |||
4828 | SourceRange ParenRange); | |||
4829 | ||||
4830 | // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if | |||
4831 | // the constructor can be elidable? | |||
4832 | ExprResult | |||
4833 | BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | |||
4834 | NamedDecl *FoundDecl, | |||
4835 | CXXConstructorDecl *Constructor, bool Elidable, | |||
4836 | MultiExprArg Exprs, bool HadMultipleCandidates, | |||
4837 | bool IsListInitialization, | |||
4838 | bool IsStdInitListInitialization, bool RequiresZeroInit, | |||
4839 | unsigned ConstructKind, SourceRange ParenRange); | |||
4840 | ||||
4841 | ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); | |||
4842 | ||||
4843 | ||||
4844 | /// Instantiate or parse a C++ default argument expression as necessary. | |||
4845 | /// Return true on error. | |||
4846 | bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, | |||
4847 | ParmVarDecl *Param); | |||
4848 | ||||
4849 | /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating | |||
4850 | /// the default expr if needed. | |||
4851 | ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, | |||
4852 | FunctionDecl *FD, | |||
4853 | ParmVarDecl *Param); | |||
4854 | ||||
4855 | /// FinalizeVarWithDestructor - Prepare for calling destructor on the | |||
4856 | /// constructed variable. | |||
4857 | void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); | |||
4858 | ||||
4859 | /// Helper class that collects exception specifications for | |||
4860 | /// implicitly-declared special member functions. | |||
4861 | class ImplicitExceptionSpecification { | |||
4862 | // Pointer to allow copying | |||
4863 | Sema *Self; | |||
4864 | // We order exception specifications thus: | |||
4865 | // noexcept is the most restrictive, but is only used in C++11. | |||
4866 | // throw() comes next. | |||
4867 | // Then a throw(collected exceptions) | |||
4868 | // Finally no specification, which is expressed as noexcept(false). | |||
4869 | // throw(...) is used instead if any called function uses it. | |||
4870 | ExceptionSpecificationType ComputedEST; | |||
4871 | llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; | |||
4872 | SmallVector<QualType, 4> Exceptions; | |||
4873 | ||||
4874 | void ClearExceptions() { | |||
4875 | ExceptionsSeen.clear(); | |||
4876 | Exceptions.clear(); | |||
4877 | } | |||
4878 | ||||
4879 | public: | |||
4880 | explicit ImplicitExceptionSpecification(Sema &Self) | |||
4881 | : Self(&Self), ComputedEST(EST_BasicNoexcept) { | |||
4882 | if (!Self.getLangOpts().CPlusPlus11) | |||
4883 | ComputedEST = EST_DynamicNone; | |||
4884 | } | |||
4885 | ||||
4886 | /// Get the computed exception specification type. | |||
4887 | ExceptionSpecificationType getExceptionSpecType() const { | |||
4888 | assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result" ) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 4889, __PRETTY_FUNCTION__)) | |||
4889 | "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result" ) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 4889, __PRETTY_FUNCTION__)); | |||
4890 | return ComputedEST; | |||
4891 | } | |||
4892 | ||||
4893 | /// The number of exceptions in the exception specification. | |||
4894 | unsigned size() const { return Exceptions.size(); } | |||
4895 | ||||
4896 | /// The set of exceptions in the exception specification. | |||
4897 | const QualType *data() const { return Exceptions.data(); } | |||
4898 | ||||
4899 | /// Integrate another called method into the collected data. | |||
4900 | void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); | |||
4901 | ||||
4902 | /// Integrate an invoked expression into the collected data. | |||
4903 | void CalledExpr(Expr *E); | |||
4904 | ||||
4905 | /// Overwrite an EPI's exception specification with this | |||
4906 | /// computed exception specification. | |||
4907 | FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { | |||
4908 | FunctionProtoType::ExceptionSpecInfo ESI; | |||
4909 | ESI.Type = getExceptionSpecType(); | |||
4910 | if (ESI.Type == EST_Dynamic) { | |||
4911 | ESI.Exceptions = Exceptions; | |||
4912 | } else if (ESI.Type == EST_None) { | |||
4913 | /// C++11 [except.spec]p14: | |||
4914 | /// The exception-specification is noexcept(false) if the set of | |||
4915 | /// potential exceptions of the special member function contains "any" | |||
4916 | ESI.Type = EST_NoexceptFalse; | |||
4917 | ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), | |||
4918 | tok::kw_false).get(); | |||
4919 | } | |||
4920 | return ESI; | |||
4921 | } | |||
4922 | }; | |||
4923 | ||||
4924 | /// Determine what sort of exception specification a defaulted | |||
4925 | /// copy constructor of a class will have. | |||
4926 | ImplicitExceptionSpecification | |||
4927 | ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, | |||
4928 | CXXMethodDecl *MD); | |||
4929 | ||||
4930 | /// Determine what sort of exception specification a defaulted | |||
4931 | /// default constructor of a class will have, and whether the parameter | |||
4932 | /// will be const. | |||
4933 | ImplicitExceptionSpecification | |||
4934 | ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); | |||
4935 | ||||
4936 | /// Determine what sort of exception specification a defaulted | |||
4937 | /// copy assignment operator of a class will have, and whether the | |||
4938 | /// parameter will be const. | |||
4939 | ImplicitExceptionSpecification | |||
4940 | ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); | |||
4941 | ||||
4942 | /// Determine what sort of exception specification a defaulted move | |||
4943 | /// constructor of a class will have. | |||
4944 | ImplicitExceptionSpecification | |||
4945 | ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); | |||
4946 | ||||
4947 | /// Determine what sort of exception specification a defaulted move | |||
4948 | /// assignment operator of a class will have. | |||
4949 | ImplicitExceptionSpecification | |||
4950 | ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); | |||
4951 | ||||
4952 | /// Determine what sort of exception specification a defaulted | |||
4953 | /// destructor of a class will have. | |||
4954 | ImplicitExceptionSpecification | |||
4955 | ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); | |||
4956 | ||||
4957 | /// Determine what sort of exception specification an inheriting | |||
4958 | /// constructor of a class will have. | |||
4959 | ImplicitExceptionSpecification | |||
4960 | ComputeInheritingCtorExceptionSpec(SourceLocation Loc, | |||
4961 | CXXConstructorDecl *CD); | |||
4962 | ||||
4963 | /// Evaluate the implicit exception specification for a defaulted | |||
4964 | /// special member function. | |||
4965 | void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); | |||
4966 | ||||
4967 | /// Check the given noexcept-specifier, convert its expression, and compute | |||
4968 | /// the appropriate ExceptionSpecificationType. | |||
4969 | ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, | |||
4970 | ExceptionSpecificationType &EST); | |||
4971 | ||||
4972 | /// Check the given exception-specification and update the | |||
4973 | /// exception specification information with the results. | |||
4974 | void checkExceptionSpecification(bool IsTopLevel, | |||
4975 | ExceptionSpecificationType EST, | |||
4976 | ArrayRef<ParsedType> DynamicExceptions, | |||
4977 | ArrayRef<SourceRange> DynamicExceptionRanges, | |||
4978 | Expr *NoexceptExpr, | |||
4979 | SmallVectorImpl<QualType> &Exceptions, | |||
4980 | FunctionProtoType::ExceptionSpecInfo &ESI); | |||
4981 | ||||
4982 | /// Determine if we're in a case where we need to (incorrectly) eagerly | |||
4983 | /// parse an exception specification to work around a libstdc++ bug. | |||
4984 | bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); | |||
4985 | ||||
4986 | /// Add an exception-specification to the given member function | |||
4987 | /// (or member function template). The exception-specification was parsed | |||
4988 | /// after the method itself was declared. | |||
4989 | void actOnDelayedExceptionSpecification(Decl *Method, | |||
4990 | ExceptionSpecificationType EST, | |||
4991 | SourceRange SpecificationRange, | |||
4992 | ArrayRef<ParsedType> DynamicExceptions, | |||
4993 | ArrayRef<SourceRange> DynamicExceptionRanges, | |||
4994 | Expr *NoexceptExpr); | |||
4995 | ||||
4996 | class InheritedConstructorInfo; | |||
4997 | ||||
4998 | /// Determine if a special member function should have a deleted | |||
4999 | /// definition when it is defaulted. | |||
5000 | bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
5001 | InheritedConstructorInfo *ICI = nullptr, | |||
5002 | bool Diagnose = false); | |||
5003 | ||||
5004 | /// Declare the implicit default constructor for the given class. | |||
5005 | /// | |||
5006 | /// \param ClassDecl The class declaration into which the implicit | |||
5007 | /// default constructor will be added. | |||
5008 | /// | |||
5009 | /// \returns The implicitly-declared default constructor. | |||
5010 | CXXConstructorDecl *DeclareImplicitDefaultConstructor( | |||
5011 | CXXRecordDecl *ClassDecl); | |||
5012 | ||||
5013 | /// DefineImplicitDefaultConstructor - Checks for feasibility of | |||
5014 | /// defining this constructor as the default constructor. | |||
5015 | void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, | |||
5016 | CXXConstructorDecl *Constructor); | |||
5017 | ||||
5018 | /// Declare the implicit destructor for the given class. | |||
5019 | /// | |||
5020 | /// \param ClassDecl The class declaration into which the implicit | |||
5021 | /// destructor will be added. | |||
5022 | /// | |||
5023 | /// \returns The implicitly-declared destructor. | |||
5024 | CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); | |||
5025 | ||||
5026 | /// DefineImplicitDestructor - Checks for feasibility of | |||
5027 | /// defining this destructor as the default destructor. | |||
5028 | void DefineImplicitDestructor(SourceLocation CurrentLocation, | |||
5029 | CXXDestructorDecl *Destructor); | |||
5030 | ||||
5031 | /// Build an exception spec for destructors that don't have one. | |||
5032 | /// | |||
5033 | /// C++11 says that user-defined destructors with no exception spec get one | |||
5034 | /// that looks as if the destructor was implicitly declared. | |||
5035 | void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); | |||
5036 | ||||
5037 | /// Define the specified inheriting constructor. | |||
5038 | void DefineInheritingConstructor(SourceLocation UseLoc, | |||
5039 | CXXConstructorDecl *Constructor); | |||
5040 | ||||
5041 | /// Declare the implicit copy constructor for the given class. | |||
5042 | /// | |||
5043 | /// \param ClassDecl The class declaration into which the implicit | |||
5044 | /// copy constructor will be added. | |||
5045 | /// | |||
5046 | /// \returns The implicitly-declared copy constructor. | |||
5047 | CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); | |||
5048 | ||||
5049 | /// DefineImplicitCopyConstructor - Checks for feasibility of | |||
5050 | /// defining this constructor as the copy constructor. | |||
5051 | void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, | |||
5052 | CXXConstructorDecl *Constructor); | |||
5053 | ||||
5054 | /// Declare the implicit move constructor for the given class. | |||
5055 | /// | |||
5056 | /// \param ClassDecl The Class declaration into which the implicit | |||
5057 | /// move constructor will be added. | |||
5058 | /// | |||
5059 | /// \returns The implicitly-declared move constructor, or NULL if it wasn't | |||
5060 | /// declared. | |||
5061 | CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); | |||
5062 | ||||
5063 | /// DefineImplicitMoveConstructor - Checks for feasibility of | |||
5064 | /// defining this constructor as the move constructor. | |||
5065 | void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, | |||
5066 | CXXConstructorDecl *Constructor); | |||
5067 | ||||
5068 | /// Declare the implicit copy assignment operator for the given class. | |||
5069 | /// | |||
5070 | /// \param ClassDecl The class declaration into which the implicit | |||
5071 | /// copy assignment operator will be added. | |||
5072 | /// | |||
5073 | /// \returns The implicitly-declared copy assignment operator. | |||
5074 | CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); | |||
5075 | ||||
5076 | /// Defines an implicitly-declared copy assignment operator. | |||
5077 | void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, | |||
5078 | CXXMethodDecl *MethodDecl); | |||
5079 | ||||
5080 | /// Declare the implicit move assignment operator for the given class. | |||
5081 | /// | |||
5082 | /// \param ClassDecl The Class declaration into which the implicit | |||
5083 | /// move assignment operator will be added. | |||
5084 | /// | |||
5085 | /// \returns The implicitly-declared move assignment operator, or NULL if it | |||
5086 | /// wasn't declared. | |||
5087 | CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); | |||
5088 | ||||
5089 | /// Defines an implicitly-declared move assignment operator. | |||
5090 | void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, | |||
5091 | CXXMethodDecl *MethodDecl); | |||
5092 | ||||
5093 | /// Force the declaration of any implicitly-declared members of this | |||
5094 | /// class. | |||
5095 | void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); | |||
5096 | ||||
5097 | /// Check a completed declaration of an implicit special member. | |||
5098 | void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); | |||
5099 | ||||
5100 | /// Determine whether the given function is an implicitly-deleted | |||
5101 | /// special member function. | |||
5102 | bool isImplicitlyDeleted(FunctionDecl *FD); | |||
5103 | ||||
5104 | /// Check whether 'this' shows up in the type of a static member | |||
5105 | /// function after the (naturally empty) cv-qualifier-seq would be. | |||
5106 | /// | |||
5107 | /// \returns true if an error occurred. | |||
5108 | bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); | |||
5109 | ||||
5110 | /// Whether this' shows up in the exception specification of a static | |||
5111 | /// member function. | |||
5112 | bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); | |||
5113 | ||||
5114 | /// Check whether 'this' shows up in the attributes of the given | |||
5115 | /// static member function. | |||
5116 | /// | |||
5117 | /// \returns true if an error occurred. | |||
5118 | bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); | |||
5119 | ||||
5120 | /// MaybeBindToTemporary - If the passed in expression has a record type with | |||
5121 | /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise | |||
5122 | /// it simply returns the passed in expression. | |||
5123 | ExprResult MaybeBindToTemporary(Expr *E); | |||
5124 | ||||
5125 | bool CompleteConstructorCall(CXXConstructorDecl *Constructor, | |||
5126 | MultiExprArg ArgsPtr, | |||
5127 | SourceLocation Loc, | |||
5128 | SmallVectorImpl<Expr*> &ConvertedArgs, | |||
5129 | bool AllowExplicit = false, | |||
5130 | bool IsListInitialization = false); | |||
5131 | ||||
5132 | ParsedType getInheritingConstructorName(CXXScopeSpec &SS, | |||
5133 | SourceLocation NameLoc, | |||
5134 | IdentifierInfo &Name); | |||
5135 | ||||
5136 | ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, | |||
5137 | Scope *S, CXXScopeSpec &SS, | |||
5138 | bool EnteringContext); | |||
5139 | ParsedType getDestructorName(SourceLocation TildeLoc, | |||
5140 | IdentifierInfo &II, SourceLocation NameLoc, | |||
5141 | Scope *S, CXXScopeSpec &SS, | |||
5142 | ParsedType ObjectType, | |||
5143 | bool EnteringContext); | |||
5144 | ||||
5145 | ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, | |||
5146 | ParsedType ObjectType); | |||
5147 | ||||
5148 | // Checks that reinterpret casts don't have undefined behavior. | |||
5149 | void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, | |||
5150 | bool IsDereference, SourceRange Range); | |||
5151 | ||||
5152 | /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. | |||
5153 | ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, | |||
5154 | tok::TokenKind Kind, | |||
5155 | SourceLocation LAngleBracketLoc, | |||
5156 | Declarator &D, | |||
5157 | SourceLocation RAngleBracketLoc, | |||
5158 | SourceLocation LParenLoc, | |||
5159 | Expr *E, | |||
5160 | SourceLocation RParenLoc); | |||
5161 | ||||
5162 | ExprResult BuildCXXNamedCast(SourceLocation OpLoc, | |||
5163 | tok::TokenKind Kind, | |||
5164 | TypeSourceInfo *Ty, | |||
5165 | Expr *E, | |||
5166 | SourceRange AngleBrackets, | |||
5167 | SourceRange Parens); | |||
5168 | ||||
5169 | ExprResult BuildCXXTypeId(QualType TypeInfoType, | |||
5170 | SourceLocation TypeidLoc, | |||
5171 | TypeSourceInfo *Operand, | |||
5172 | SourceLocation RParenLoc); | |||
5173 | ExprResult BuildCXXTypeId(QualType TypeInfoType, | |||
5174 | SourceLocation TypeidLoc, | |||
5175 | Expr *Operand, | |||
5176 | SourceLocation RParenLoc); | |||
5177 | ||||
5178 | /// ActOnCXXTypeid - Parse typeid( something ). | |||
5179 | ExprResult ActOnCXXTypeid(SourceLocation OpLoc, | |||
5180 | SourceLocation LParenLoc, bool isType, | |||
5181 | void *TyOrExpr, | |||
5182 | SourceLocation RParenLoc); | |||
5183 | ||||
5184 | ExprResult BuildCXXUuidof(QualType TypeInfoType, | |||
5185 | SourceLocation TypeidLoc, | |||
5186 | TypeSourceInfo *Operand, | |||
5187 | SourceLocation RParenLoc); | |||
5188 | ExprResult BuildCXXUuidof(QualType TypeInfoType, | |||
5189 | SourceLocation TypeidLoc, | |||
5190 | Expr *Operand, | |||
5191 | SourceLocation RParenLoc); | |||
5192 | ||||
5193 | /// ActOnCXXUuidof - Parse __uuidof( something ). | |||
5194 | ExprResult ActOnCXXUuidof(SourceLocation OpLoc, | |||
5195 | SourceLocation LParenLoc, bool isType, | |||
5196 | void *TyOrExpr, | |||
5197 | SourceLocation RParenLoc); | |||
5198 | ||||
5199 | /// Handle a C++1z fold-expression: ( expr op ... op expr ). | |||
5200 | ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, | |||
5201 | tok::TokenKind Operator, | |||
5202 | SourceLocation EllipsisLoc, Expr *RHS, | |||
5203 | SourceLocation RParenLoc); | |||
5204 | ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, | |||
5205 | BinaryOperatorKind Operator, | |||
5206 | SourceLocation EllipsisLoc, Expr *RHS, | |||
5207 | SourceLocation RParenLoc); | |||
5208 | ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, | |||
5209 | BinaryOperatorKind Operator); | |||
5210 | ||||
5211 | //// ActOnCXXThis - Parse 'this' pointer. | |||
5212 | ExprResult ActOnCXXThis(SourceLocation loc); | |||
5213 | ||||
5214 | /// Try to retrieve the type of the 'this' pointer. | |||
5215 | /// | |||
5216 | /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. | |||
5217 | QualType getCurrentThisType(); | |||
5218 | ||||
5219 | /// When non-NULL, the C++ 'this' expression is allowed despite the | |||
5220 | /// current context not being a non-static member function. In such cases, | |||
5221 | /// this provides the type used for 'this'. | |||
5222 | QualType CXXThisTypeOverride; | |||
5223 | ||||
5224 | /// RAII object used to temporarily allow the C++ 'this' expression | |||
5225 | /// to be used, with the given qualifiers on the current class type. | |||
5226 | class CXXThisScopeRAII { | |||
5227 | Sema &S; | |||
5228 | QualType OldCXXThisTypeOverride; | |||
5229 | bool Enabled; | |||
5230 | ||||
5231 | public: | |||
5232 | /// Introduce a new scope where 'this' may be allowed (when enabled), | |||
5233 | /// using the given declaration (which is either a class template or a | |||
5234 | /// class) along with the given qualifiers. | |||
5235 | /// along with the qualifiers placed on '*this'. | |||
5236 | CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, | |||
5237 | bool Enabled = true); | |||
5238 | ||||
5239 | ~CXXThisScopeRAII(); | |||
5240 | }; | |||
5241 | ||||
5242 | /// Make sure the value of 'this' is actually available in the current | |||
5243 | /// context, if it is a potentially evaluated context. | |||
5244 | /// | |||
5245 | /// \param Loc The location at which the capture of 'this' occurs. | |||
5246 | /// | |||
5247 | /// \param Explicit Whether 'this' is explicitly captured in a lambda | |||
5248 | /// capture list. | |||
5249 | /// | |||
5250 | /// \param FunctionScopeIndexToStopAt If non-null, it points to the index | |||
5251 | /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. | |||
5252 | /// This is useful when enclosing lambdas must speculatively capture | |||
5253 | /// 'this' that may or may not be used in certain specializations of | |||
5254 | /// a nested generic lambda (depending on whether the name resolves to | |||
5255 | /// a non-static member function or a static function). | |||
5256 | /// \return returns 'true' if failed, 'false' if success. | |||
5257 | bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, | |||
5258 | bool BuildAndDiagnose = true, | |||
5259 | const unsigned *const FunctionScopeIndexToStopAt = nullptr, | |||
5260 | bool ByCopy = false); | |||
5261 | ||||
5262 | /// Determine whether the given type is the type of *this that is used | |||
5263 | /// outside of the body of a member function for a type that is currently | |||
5264 | /// being defined. | |||
5265 | bool isThisOutsideMemberFunctionBody(QualType BaseType); | |||
5266 | ||||
5267 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. | |||
5268 | ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); | |||
5269 | ||||
5270 | ||||
5271 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. | |||
5272 | ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); | |||
5273 | ||||
5274 | ExprResult | |||
5275 | ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, | |||
5276 | SourceLocation AtLoc, SourceLocation RParen); | |||
5277 | ||||
5278 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. | |||
5279 | ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); | |||
5280 | ||||
5281 | //// ActOnCXXThrow - Parse throw expressions. | |||
5282 | ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); | |||
5283 | ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, | |||
5284 | bool IsThrownVarInScope); | |||
5285 | bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); | |||
5286 | ||||
5287 | /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. | |||
5288 | /// Can be interpreted either as function-style casting ("int(x)") | |||
5289 | /// or class type construction ("ClassType(x,y,z)") | |||
5290 | /// or creation of a value-initialized type ("int()"). | |||
5291 | ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, | |||
5292 | SourceLocation LParenOrBraceLoc, | |||
5293 | MultiExprArg Exprs, | |||
5294 | SourceLocation RParenOrBraceLoc, | |||
5295 | bool ListInitialization); | |||
5296 | ||||
5297 | ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, | |||
5298 | SourceLocation LParenLoc, | |||
5299 | MultiExprArg Exprs, | |||
5300 | SourceLocation RParenLoc, | |||
5301 | bool ListInitialization); | |||
5302 | ||||
5303 | /// ActOnCXXNew - Parsed a C++ 'new' expression. | |||
5304 | ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, | |||
5305 | SourceLocation PlacementLParen, | |||
5306 | MultiExprArg PlacementArgs, | |||
5307 | SourceLocation PlacementRParen, | |||
5308 | SourceRange TypeIdParens, Declarator &D, | |||
5309 | Expr *Initializer); | |||
5310 | ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, | |||
5311 | SourceLocation PlacementLParen, | |||
5312 | MultiExprArg PlacementArgs, | |||
5313 | SourceLocation PlacementRParen, | |||
5314 | SourceRange TypeIdParens, | |||
5315 | QualType AllocType, | |||
5316 | TypeSourceInfo *AllocTypeInfo, | |||
5317 | Optional<Expr *> ArraySize, | |||
5318 | SourceRange DirectInitRange, | |||
5319 | Expr *Initializer); | |||
5320 | ||||
5321 | /// Determine whether \p FD is an aligned allocation or deallocation | |||
5322 | /// function that is unavailable. | |||
5323 | bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; | |||
5324 | ||||
5325 | /// Produce diagnostics if \p FD is an aligned allocation or deallocation | |||
5326 | /// function that is unavailable. | |||
5327 | void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, | |||
5328 | SourceLocation Loc); | |||
5329 | ||||
5330 | bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, | |||
5331 | SourceRange R); | |||
5332 | ||||
5333 | /// The scope in which to find allocation functions. | |||
5334 | enum AllocationFunctionScope { | |||
5335 | /// Only look for allocation functions in the global scope. | |||
5336 | AFS_Global, | |||
5337 | /// Only look for allocation functions in the scope of the | |||
5338 | /// allocated class. | |||
5339 | AFS_Class, | |||
5340 | /// Look for allocation functions in both the global scope | |||
5341 | /// and in the scope of the allocated class. | |||
5342 | AFS_Both | |||
5343 | }; | |||
5344 | ||||
5345 | /// Finds the overloads of operator new and delete that are appropriate | |||
5346 | /// for the allocation. | |||
5347 | bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, | |||
5348 | AllocationFunctionScope NewScope, | |||
5349 | AllocationFunctionScope DeleteScope, | |||
5350 | QualType AllocType, bool IsArray, | |||
5351 | bool &PassAlignment, MultiExprArg PlaceArgs, | |||
5352 | FunctionDecl *&OperatorNew, | |||
5353 | FunctionDecl *&OperatorDelete, | |||
5354 | bool Diagnose = true); | |||
5355 | void DeclareGlobalNewDelete(); | |||
5356 | void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, | |||
5357 | ArrayRef<QualType> Params); | |||
5358 | ||||
5359 | bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, | |||
5360 | DeclarationName Name, FunctionDecl* &Operator, | |||
5361 | bool Diagnose = true); | |||
5362 | FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, | |||
5363 | bool CanProvideSize, | |||
5364 | bool Overaligned, | |||
5365 | DeclarationName Name); | |||
5366 | FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, | |||
5367 | CXXRecordDecl *RD); | |||
5368 | ||||
5369 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression | |||
5370 | ExprResult ActOnCXXDelete(SourceLocation StartLoc, | |||
5371 | bool UseGlobal, bool ArrayForm, | |||
5372 | Expr *Operand); | |||
5373 | void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, | |||
5374 | bool IsDelete, bool CallCanBeVirtual, | |||
5375 | bool WarnOnNonAbstractTypes, | |||
5376 | SourceLocation DtorLoc); | |||
5377 | ||||
5378 | ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, | |||
5379 | Expr *Operand, SourceLocation RParen); | |||
5380 | ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, | |||
5381 | SourceLocation RParen); | |||
5382 | ||||
5383 | /// Parsed one of the type trait support pseudo-functions. | |||
5384 | ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5385 | ArrayRef<ParsedType> Args, | |||
5386 | SourceLocation RParenLoc); | |||
5387 | ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5388 | ArrayRef<TypeSourceInfo *> Args, | |||
5389 | SourceLocation RParenLoc); | |||
5390 | ||||
5391 | /// ActOnArrayTypeTrait - Parsed one of the binary type trait support | |||
5392 | /// pseudo-functions. | |||
5393 | ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, | |||
5394 | SourceLocation KWLoc, | |||
5395 | ParsedType LhsTy, | |||
5396 | Expr *DimExpr, | |||
5397 | SourceLocation RParen); | |||
5398 | ||||
5399 | ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, | |||
5400 | SourceLocation KWLoc, | |||
5401 | TypeSourceInfo *TSInfo, | |||
5402 | Expr *DimExpr, | |||
5403 | SourceLocation RParen); | |||
5404 | ||||
5405 | /// ActOnExpressionTrait - Parsed one of the unary type trait support | |||
5406 | /// pseudo-functions. | |||
5407 | ExprResult ActOnExpressionTrait(ExpressionTrait OET, | |||
5408 | SourceLocation KWLoc, | |||
5409 | Expr *Queried, | |||
5410 | SourceLocation RParen); | |||
5411 | ||||
5412 | ExprResult BuildExpressionTrait(ExpressionTrait OET, | |||
5413 | SourceLocation KWLoc, | |||
5414 | Expr *Queried, | |||
5415 | SourceLocation RParen); | |||
5416 | ||||
5417 | ExprResult ActOnStartCXXMemberReference(Scope *S, | |||
5418 | Expr *Base, | |||
5419 | SourceLocation OpLoc, | |||
5420 | tok::TokenKind OpKind, | |||
5421 | ParsedType &ObjectType, | |||
5422 | bool &MayBePseudoDestructor); | |||
5423 | ||||
5424 | ExprResult BuildPseudoDestructorExpr(Expr *Base, | |||
5425 | SourceLocation OpLoc, | |||
5426 | tok::TokenKind OpKind, | |||
5427 | const CXXScopeSpec &SS, | |||
5428 | TypeSourceInfo *ScopeType, | |||
5429 | SourceLocation CCLoc, | |||
5430 | SourceLocation TildeLoc, | |||
5431 | PseudoDestructorTypeStorage DestroyedType); | |||
5432 | ||||
5433 | ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
5434 | SourceLocation OpLoc, | |||
5435 | tok::TokenKind OpKind, | |||
5436 | CXXScopeSpec &SS, | |||
5437 | UnqualifiedId &FirstTypeName, | |||
5438 | SourceLocation CCLoc, | |||
5439 | SourceLocation TildeLoc, | |||
5440 | UnqualifiedId &SecondTypeName); | |||
5441 | ||||
5442 | ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
5443 | SourceLocation OpLoc, | |||
5444 | tok::TokenKind OpKind, | |||
5445 | SourceLocation TildeLoc, | |||
5446 | const DeclSpec& DS); | |||
5447 | ||||
5448 | /// MaybeCreateExprWithCleanups - If the current full-expression | |||
5449 | /// requires any cleanups, surround it with a ExprWithCleanups node. | |||
5450 | /// Otherwise, just returns the passed-in expression. | |||
5451 | Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); | |||
5452 | Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); | |||
5453 | ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); | |||
5454 | ||||
5455 | MaterializeTemporaryExpr * | |||
5456 | CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, | |||
5457 | bool BoundToLvalueReference); | |||
5458 | ||||
5459 | ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { | |||
5460 | return ActOnFinishFullExpr( | |||
5461 | Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); | |||
5462 | } | |||
5463 | ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, | |||
5464 | bool DiscardedValue, bool IsConstexpr = false); | |||
5465 | StmtResult ActOnFinishFullStmt(Stmt *Stmt); | |||
5466 | ||||
5467 | // Marks SS invalid if it represents an incomplete type. | |||
5468 | bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); | |||
5469 | ||||
5470 | DeclContext *computeDeclContext(QualType T); | |||
5471 | DeclContext *computeDeclContext(const CXXScopeSpec &SS, | |||
5472 | bool EnteringContext = false); | |||
5473 | bool isDependentScopeSpecifier(const CXXScopeSpec &SS); | |||
5474 | CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); | |||
5475 | ||||
5476 | /// The parser has parsed a global nested-name-specifier '::'. | |||
5477 | /// | |||
5478 | /// \param CCLoc The location of the '::'. | |||
5479 | /// | |||
5480 | /// \param SS The nested-name-specifier, which will be updated in-place | |||
5481 | /// to reflect the parsed nested-name-specifier. | |||
5482 | /// | |||
5483 | /// \returns true if an error occurred, false otherwise. | |||
5484 | bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); | |||
5485 | ||||
5486 | /// The parser has parsed a '__super' nested-name-specifier. | |||
5487 | /// | |||
5488 | /// \param SuperLoc The location of the '__super' keyword. | |||
5489 | /// | |||
5490 | /// \param ColonColonLoc The location of the '::'. | |||
5491 | /// | |||
5492 | /// \param SS The nested-name-specifier, which will be updated in-place | |||
5493 | /// to reflect the parsed nested-name-specifier. | |||
5494 | /// | |||
5495 | /// \returns true if an error occurred, false otherwise. | |||
5496 | bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, | |||
5497 | SourceLocation ColonColonLoc, CXXScopeSpec &SS); | |||
5498 | ||||
5499 | bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, | |||
5500 | bool *CanCorrect = nullptr); | |||
5501 | NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); | |||
5502 | ||||
5503 | /// Keeps information about an identifier in a nested-name-spec. | |||
5504 | /// | |||
5505 | struct NestedNameSpecInfo { | |||
5506 | /// The type of the object, if we're parsing nested-name-specifier in | |||
5507 | /// a member access expression. | |||
5508 | ParsedType ObjectType; | |||
5509 | ||||
5510 | /// The identifier preceding the '::'. | |||
5511 | IdentifierInfo *Identifier; | |||
5512 | ||||
5513 | /// The location of the identifier. | |||
5514 | SourceLocation IdentifierLoc; | |||
5515 | ||||
5516 | /// The location of the '::'. | |||
5517 | SourceLocation CCLoc; | |||
5518 | ||||
5519 | /// Creates info object for the most typical case. | |||
5520 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, | |||
5521 | SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) | |||
5522 | : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), | |||
5523 | CCLoc(ColonColonLoc) { | |||
5524 | } | |||
5525 | ||||
5526 | NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, | |||
5527 | SourceLocation ColonColonLoc, QualType ObjectType) | |||
5528 | : ObjectType(ParsedType::make(ObjectType)), Identifier(II), | |||
5529 | IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { | |||
5530 | } | |||
5531 | }; | |||
5532 | ||||
5533 | bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, | |||
5534 | NestedNameSpecInfo &IdInfo); | |||
5535 | ||||
5536 | bool BuildCXXNestedNameSpecifier(Scope *S, | |||
5537 | NestedNameSpecInfo &IdInfo, | |||
5538 | bool EnteringContext, | |||
5539 | CXXScopeSpec &SS, | |||
5540 | NamedDecl *ScopeLookupResult, | |||
5541 | bool ErrorRecoveryLookup, | |||
5542 | bool *IsCorrectedToColon = nullptr, | |||
5543 | bool OnlyNamespace = false); | |||
5544 | ||||
5545 | /// The parser has parsed a nested-name-specifier 'identifier::'. | |||
5546 | /// | |||
5547 | /// \param S The scope in which this nested-name-specifier occurs. | |||
5548 | /// | |||
5549 | /// \param IdInfo Parser information about an identifier in the | |||
5550 | /// nested-name-spec. | |||
5551 | /// | |||
5552 | /// \param EnteringContext Whether we're entering the context nominated by | |||
5553 | /// this nested-name-specifier. | |||
5554 | /// | |||
5555 | /// \param SS The nested-name-specifier, which is both an input | |||
5556 | /// parameter (the nested-name-specifier before this type) and an | |||
5557 | /// output parameter (containing the full nested-name-specifier, | |||
5558 | /// including this new type). | |||
5559 | /// | |||
5560 | /// \param ErrorRecoveryLookup If true, then this method is called to improve | |||
5561 | /// error recovery. In this case do not emit error message. | |||
5562 | /// | |||
5563 | /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' | |||
5564 | /// are allowed. The bool value pointed by this parameter is set to 'true' | |||
5565 | /// if the identifier is treated as if it was followed by ':', not '::'. | |||
5566 | /// | |||
5567 | /// \param OnlyNamespace If true, only considers namespaces in lookup. | |||
5568 | /// | |||
5569 | /// \returns true if an error occurred, false otherwise. | |||
5570 | bool ActOnCXXNestedNameSpecifier(Scope *S, | |||
5571 | NestedNameSpecInfo &IdInfo, | |||
5572 | bool EnteringContext, | |||
5573 | CXXScopeSpec &SS, | |||
5574 | bool ErrorRecoveryLookup = false, | |||
5575 | bool *IsCorrectedToColon = nullptr, | |||
5576 | bool OnlyNamespace = false); | |||
5577 | ||||
5578 | ExprResult ActOnDecltypeExpression(Expr *E); | |||
5579 | ||||
5580 | bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, | |||
5581 | const DeclSpec &DS, | |||
5582 | SourceLocation ColonColonLoc); | |||
5583 | ||||
5584 | bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, | |||
5585 | NestedNameSpecInfo &IdInfo, | |||
5586 | bool EnteringContext); | |||
5587 | ||||
5588 | /// The parser has parsed a nested-name-specifier | |||
5589 | /// 'template[opt] template-name < template-args >::'. | |||
5590 | /// | |||
5591 | /// \param S The scope in which this nested-name-specifier occurs. | |||
5592 | /// | |||
5593 | /// \param SS The nested-name-specifier, which is both an input | |||
5594 | /// parameter (the nested-name-specifier before this type) and an | |||
5595 | /// output parameter (containing the full nested-name-specifier, | |||
5596 | /// including this new type). | |||
5597 | /// | |||
5598 | /// \param TemplateKWLoc the location of the 'template' keyword, if any. | |||
5599 | /// \param TemplateName the template name. | |||
5600 | /// \param TemplateNameLoc The location of the template name. | |||
5601 | /// \param LAngleLoc The location of the opening angle bracket ('<'). | |||
5602 | /// \param TemplateArgs The template arguments. | |||
5603 | /// \param RAngleLoc The location of the closing angle bracket ('>'). | |||
5604 | /// \param CCLoc The location of the '::'. | |||
5605 | /// | |||
5606 | /// \param EnteringContext Whether we're entering the context of the | |||
5607 | /// nested-name-specifier. | |||
5608 | /// | |||
5609 | /// | |||
5610 | /// \returns true if an error occurred, false otherwise. | |||
5611 | bool ActOnCXXNestedNameSpecifier(Scope *S, | |||
5612 | CXXScopeSpec &SS, | |||
5613 | SourceLocation TemplateKWLoc, | |||
5614 | TemplateTy TemplateName, | |||
5615 | SourceLocation TemplateNameLoc, | |||
5616 | SourceLocation LAngleLoc, | |||
5617 | ASTTemplateArgsPtr TemplateArgs, | |||
5618 | SourceLocation RAngleLoc, | |||
5619 | SourceLocation CCLoc, | |||
5620 | bool EnteringContext); | |||
5621 | ||||
5622 | /// Given a C++ nested-name-specifier, produce an annotation value | |||
5623 | /// that the parser can use later to reconstruct the given | |||
5624 | /// nested-name-specifier. | |||
5625 | /// | |||
5626 | /// \param SS A nested-name-specifier. | |||
5627 | /// | |||
5628 | /// \returns A pointer containing all of the information in the | |||
5629 | /// nested-name-specifier \p SS. | |||
5630 | void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); | |||
5631 | ||||
5632 | /// Given an annotation pointer for a nested-name-specifier, restore | |||
5633 | /// the nested-name-specifier structure. | |||
5634 | /// | |||
5635 | /// \param Annotation The annotation pointer, produced by | |||
5636 | /// \c SaveNestedNameSpecifierAnnotation(). | |||
5637 | /// | |||
5638 | /// \param AnnotationRange The source range corresponding to the annotation. | |||
5639 | /// | |||
5640 | /// \param SS The nested-name-specifier that will be updated with the contents | |||
5641 | /// of the annotation pointer. | |||
5642 | void RestoreNestedNameSpecifierAnnotation(void *Annotation, | |||
5643 | SourceRange AnnotationRange, | |||
5644 | CXXScopeSpec &SS); | |||
5645 | ||||
5646 | bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); | |||
5647 | ||||
5648 | /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global | |||
5649 | /// scope or nested-name-specifier) is parsed, part of a declarator-id. | |||
5650 | /// After this method is called, according to [C++ 3.4.3p3], names should be | |||
5651 | /// looked up in the declarator-id's scope, until the declarator is parsed and | |||
5652 | /// ActOnCXXExitDeclaratorScope is called. | |||
5653 | /// The 'SS' should be a non-empty valid CXXScopeSpec. | |||
5654 | bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); | |||
5655 | ||||
5656 | /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously | |||
5657 | /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same | |||
5658 | /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. | |||
5659 | /// Used to indicate that names should revert to being looked up in the | |||
5660 | /// defining scope. | |||
5661 | void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); | |||
5662 | ||||
5663 | /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an | |||
5664 | /// initializer for the declaration 'Dcl'. | |||
5665 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a | |||
5666 | /// static data member of class X, names should be looked up in the scope of | |||
5667 | /// class X. | |||
5668 | void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); | |||
5669 | ||||
5670 | /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an | |||
5671 | /// initializer for the declaration 'Dcl'. | |||
5672 | void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); | |||
5673 | ||||
5674 | /// Create a new lambda closure type. | |||
5675 | CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, | |||
5676 | TypeSourceInfo *Info, | |||
5677 | bool KnownDependent, | |||
5678 | LambdaCaptureDefault CaptureDefault); | |||
5679 | ||||
5680 | /// Start the definition of a lambda expression. | |||
5681 | CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, | |||
5682 | SourceRange IntroducerRange, | |||
5683 | TypeSourceInfo *MethodType, | |||
5684 | SourceLocation EndLoc, | |||
5685 | ArrayRef<ParmVarDecl *> Params, | |||
5686 | bool IsConstexprSpecified); | |||
5687 | ||||
5688 | /// Endow the lambda scope info with the relevant properties. | |||
5689 | void buildLambdaScope(sema::LambdaScopeInfo *LSI, | |||
5690 | CXXMethodDecl *CallOperator, | |||
5691 | SourceRange IntroducerRange, | |||
5692 | LambdaCaptureDefault CaptureDefault, | |||
5693 | SourceLocation CaptureDefaultLoc, | |||
5694 | bool ExplicitParams, | |||
5695 | bool ExplicitResultType, | |||
5696 | bool Mutable); | |||
5697 | ||||
5698 | /// Perform initialization analysis of the init-capture and perform | |||
5699 | /// any implicit conversions such as an lvalue-to-rvalue conversion if | |||
5700 | /// not being used to initialize a reference. | |||
5701 | ParsedType actOnLambdaInitCaptureInitialization( | |||
5702 | SourceLocation Loc, bool ByRef, IdentifierInfo *Id, | |||
5703 | LambdaCaptureInitKind InitKind, Expr *&Init) { | |||
5704 | return ParsedType::make(buildLambdaInitCaptureInitialization( | |||
5705 | Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); | |||
5706 | } | |||
5707 | QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, | |||
5708 | IdentifierInfo *Id, | |||
5709 | bool DirectInit, Expr *&Init); | |||
5710 | ||||
5711 | /// Create a dummy variable within the declcontext of the lambda's | |||
5712 | /// call operator, for name lookup purposes for a lambda init capture. | |||
5713 | /// | |||
5714 | /// CodeGen handles emission of lambda captures, ignoring these dummy | |||
5715 | /// variables appropriately. | |||
5716 | VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, | |||
5717 | QualType InitCaptureType, | |||
5718 | IdentifierInfo *Id, | |||
5719 | unsigned InitStyle, Expr *Init); | |||
5720 | ||||
5721 | /// Build the implicit field for an init-capture. | |||
5722 | FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var); | |||
5723 | ||||
5724 | /// Note that we have finished the explicit captures for the | |||
5725 | /// given lambda. | |||
5726 | void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); | |||
5727 | ||||
5728 | /// \brief This is called after parsing the explicit template parameter list | |||
5729 | /// on a lambda (if it exists) in C++2a. | |||
5730 | void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, | |||
5731 | ArrayRef<NamedDecl *> TParams, | |||
5732 | SourceLocation RAngleLoc); | |||
5733 | ||||
5734 | /// Introduce the lambda parameters into scope. | |||
5735 | void addLambdaParameters( | |||
5736 | ArrayRef<LambdaIntroducer::LambdaCapture> Captures, | |||
5737 | CXXMethodDecl *CallOperator, Scope *CurScope); | |||
5738 | ||||
5739 | /// Deduce a block or lambda's return type based on the return | |||
5740 | /// statements present in the body. | |||
5741 | void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); | |||
5742 | ||||
5743 | /// ActOnStartOfLambdaDefinition - This is called just before we start | |||
5744 | /// parsing the body of a lambda; it analyzes the explicit captures and | |||
5745 | /// arguments, and sets up various data-structures for the body of the | |||
5746 | /// lambda. | |||
5747 | void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, | |||
5748 | Declarator &ParamInfo, Scope *CurScope); | |||
5749 | ||||
5750 | /// ActOnLambdaError - If there is an error parsing a lambda, this callback | |||
5751 | /// is invoked to pop the information about the lambda. | |||
5752 | void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, | |||
5753 | bool IsInstantiation = false); | |||
5754 | ||||
5755 | /// ActOnLambdaExpr - This is called when the body of a lambda expression | |||
5756 | /// was successfully completed. | |||
5757 | ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, | |||
5758 | Scope *CurScope); | |||
5759 | ||||
5760 | /// Does copying/destroying the captured variable have side effects? | |||
5761 | bool CaptureHasSideEffects(const sema::Capture &From); | |||
5762 | ||||
5763 | /// Diagnose if an explicit lambda capture is unused. Returns true if a | |||
5764 | /// diagnostic is emitted. | |||
5765 | bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, | |||
5766 | const sema::Capture &From); | |||
5767 | ||||
5768 | /// Complete a lambda-expression having processed and attached the | |||
5769 | /// lambda body. | |||
5770 | ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, | |||
5771 | sema::LambdaScopeInfo *LSI); | |||
5772 | ||||
5773 | /// Get the return type to use for a lambda's conversion function(s) to | |||
5774 | /// function pointer type, given the type of the call operator. | |||
5775 | QualType | |||
5776 | getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); | |||
5777 | ||||
5778 | /// Define the "body" of the conversion from a lambda object to a | |||
5779 | /// function pointer. | |||
5780 | /// | |||
5781 | /// This routine doesn't actually define a sensible body; rather, it fills | |||
5782 | /// in the initialization expression needed to copy the lambda object into | |||
5783 | /// the block, and IR generation actually generates the real body of the | |||
5784 | /// block pointer conversion. | |||
5785 | void DefineImplicitLambdaToFunctionPointerConversion( | |||
5786 | SourceLocation CurrentLoc, CXXConversionDecl *Conv); | |||
5787 | ||||
5788 | /// Define the "body" of the conversion from a lambda object to a | |||
5789 | /// block pointer. | |||
5790 | /// | |||
5791 | /// This routine doesn't actually define a sensible body; rather, it fills | |||
5792 | /// in the initialization expression needed to copy the lambda object into | |||
5793 | /// the block, and IR generation actually generates the real body of the | |||
5794 | /// block pointer conversion. | |||
5795 | void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, | |||
5796 | CXXConversionDecl *Conv); | |||
5797 | ||||
5798 | ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, | |||
5799 | SourceLocation ConvLocation, | |||
5800 | CXXConversionDecl *Conv, | |||
5801 | Expr *Src); | |||
5802 | ||||
5803 | // ParseObjCStringLiteral - Parse Objective-C string literals. | |||
5804 | ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, | |||
5805 | ArrayRef<Expr *> Strings); | |||
5806 | ||||
5807 | ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); | |||
5808 | ||||
5809 | /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the | |||
5810 | /// numeric literal expression. Type of the expression will be "NSNumber *" | |||
5811 | /// or "id" if NSNumber is unavailable. | |||
5812 | ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); | |||
5813 | ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, | |||
5814 | bool Value); | |||
5815 | ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); | |||
5816 | ||||
5817 | /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the | |||
5818 | /// '@' prefixed parenthesized expression. The type of the expression will | |||
5819 | /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type | |||
5820 | /// of ValueType, which is allowed to be a built-in numeric type, "char *", | |||
5821 | /// "const char *" or C structure with attribute 'objc_boxable'. | |||
5822 | ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); | |||
5823 | ||||
5824 | ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, | |||
5825 | Expr *IndexExpr, | |||
5826 | ObjCMethodDecl *getterMethod, | |||
5827 | ObjCMethodDecl *setterMethod); | |||
5828 | ||||
5829 | ExprResult BuildObjCDictionaryLiteral(SourceRange SR, | |||
5830 | MutableArrayRef<ObjCDictionaryElement> Elements); | |||
5831 | ||||
5832 | ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, | |||
5833 | TypeSourceInfo *EncodedTypeInfo, | |||
5834 | SourceLocation RParenLoc); | |||
5835 | ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, | |||
5836 | CXXConversionDecl *Method, | |||
5837 | bool HadMultipleCandidates); | |||
5838 | ||||
5839 | ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, | |||
5840 | SourceLocation EncodeLoc, | |||
5841 | SourceLocation LParenLoc, | |||
5842 | ParsedType Ty, | |||
5843 | SourceLocation RParenLoc); | |||
5844 | ||||
5845 | /// ParseObjCSelectorExpression - Build selector expression for \@selector | |||
5846 | ExprResult ParseObjCSelectorExpression(Selector Sel, | |||
5847 | SourceLocation AtLoc, | |||
5848 | SourceLocation SelLoc, | |||
5849 | SourceLocation LParenLoc, | |||
5850 | SourceLocation RParenLoc, | |||
5851 | bool WarnMultipleSelectors); | |||
5852 | ||||
5853 | /// ParseObjCProtocolExpression - Build protocol expression for \@protocol | |||
5854 | ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, | |||
5855 | SourceLocation AtLoc, | |||
5856 | SourceLocation ProtoLoc, | |||
5857 | SourceLocation LParenLoc, | |||
5858 | SourceLocation ProtoIdLoc, | |||
5859 | SourceLocation RParenLoc); | |||
5860 | ||||
5861 | //===--------------------------------------------------------------------===// | |||
5862 | // C++ Declarations | |||
5863 | // | |||
5864 | Decl *ActOnStartLinkageSpecification(Scope *S, | |||
5865 | SourceLocation ExternLoc, | |||
5866 | Expr *LangStr, | |||
5867 | SourceLocation LBraceLoc); | |||
5868 | Decl *ActOnFinishLinkageSpecification(Scope *S, | |||
5869 | Decl *LinkageSpec, | |||
5870 | SourceLocation RBraceLoc); | |||
5871 | ||||
5872 | ||||
5873 | //===--------------------------------------------------------------------===// | |||
5874 | // C++ Classes | |||
5875 | // | |||
5876 | CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); | |||
5877 | bool isCurrentClassName(const IdentifierInfo &II, Scope *S, | |||
5878 | const CXXScopeSpec *SS = nullptr); | |||
5879 | bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); | |||
5880 | ||||
5881 | bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, | |||
5882 | SourceLocation ColonLoc, | |||
5883 | const ParsedAttributesView &Attrs); | |||
5884 | ||||
5885 | NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, | |||
5886 | Declarator &D, | |||
5887 | MultiTemplateParamsArg TemplateParameterLists, | |||
5888 | Expr *BitfieldWidth, const VirtSpecifiers &VS, | |||
5889 | InClassInitStyle InitStyle); | |||
5890 | ||||
5891 | void ActOnStartCXXInClassMemberInitializer(); | |||
5892 | void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, | |||
5893 | SourceLocation EqualLoc, | |||
5894 | Expr *Init); | |||
5895 | ||||
5896 | MemInitResult ActOnMemInitializer(Decl *ConstructorD, | |||
5897 | Scope *S, | |||
5898 | CXXScopeSpec &SS, | |||
5899 | IdentifierInfo *MemberOrBase, | |||
5900 | ParsedType TemplateTypeTy, | |||
5901 | const DeclSpec &DS, | |||
5902 | SourceLocation IdLoc, | |||
5903 | SourceLocation LParenLoc, | |||
5904 | ArrayRef<Expr *> Args, | |||
5905 | SourceLocation RParenLoc, | |||
5906 | SourceLocation EllipsisLoc); | |||
5907 | ||||
5908 | MemInitResult ActOnMemInitializer(Decl *ConstructorD, | |||
5909 | Scope *S, | |||
5910 | CXXScopeSpec &SS, | |||
5911 | IdentifierInfo *MemberOrBase, | |||
5912 | ParsedType TemplateTypeTy, | |||
5913 | const DeclSpec &DS, | |||
5914 | SourceLocation IdLoc, | |||
5915 | Expr *InitList, | |||
5916 | SourceLocation EllipsisLoc); | |||
5917 | ||||
5918 | MemInitResult BuildMemInitializer(Decl *ConstructorD, | |||
5919 | Scope *S, | |||
5920 | CXXScopeSpec &SS, | |||
5921 | IdentifierInfo *MemberOrBase, | |||
5922 | ParsedType TemplateTypeTy, | |||
5923 | const DeclSpec &DS, | |||
5924 | SourceLocation IdLoc, | |||
5925 | Expr *Init, | |||
5926 | SourceLocation EllipsisLoc); | |||
5927 | ||||
5928 | MemInitResult BuildMemberInitializer(ValueDecl *Member, | |||
5929 | Expr *Init, | |||
5930 | SourceLocation IdLoc); | |||
5931 | ||||
5932 | MemInitResult BuildBaseInitializer(QualType BaseType, | |||
5933 | TypeSourceInfo *BaseTInfo, | |||
5934 | Expr *Init, | |||
5935 | CXXRecordDecl *ClassDecl, | |||
5936 | SourceLocation EllipsisLoc); | |||
5937 | ||||
5938 | MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, | |||
5939 | Expr *Init, | |||
5940 | CXXRecordDecl *ClassDecl); | |||
5941 | ||||
5942 | bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, | |||
5943 | CXXCtorInitializer *Initializer); | |||
5944 | ||||
5945 | bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, | |||
5946 | ArrayRef<CXXCtorInitializer *> Initializers = None); | |||
5947 | ||||
5948 | void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); | |||
5949 | ||||
5950 | ||||
5951 | /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, | |||
5952 | /// mark all the non-trivial destructors of its members and bases as | |||
5953 | /// referenced. | |||
5954 | void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, | |||
5955 | CXXRecordDecl *Record); | |||
5956 | ||||
5957 | /// The list of classes whose vtables have been used within | |||
5958 | /// this translation unit, and the source locations at which the | |||
5959 | /// first use occurred. | |||
5960 | typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; | |||
5961 | ||||
5962 | /// The list of vtables that are required but have not yet been | |||
5963 | /// materialized. | |||
5964 | SmallVector<VTableUse, 16> VTableUses; | |||
5965 | ||||
5966 | /// The set of classes whose vtables have been used within | |||
5967 | /// this translation unit, and a bit that will be true if the vtable is | |||
5968 | /// required to be emitted (otherwise, it should be emitted only if needed | |||
5969 | /// by code generation). | |||
5970 | llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; | |||
5971 | ||||
5972 | /// Load any externally-stored vtable uses. | |||
5973 | void LoadExternalVTableUses(); | |||
5974 | ||||
5975 | /// Note that the vtable for the given class was used at the | |||
5976 | /// given location. | |||
5977 | void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, | |||
5978 | bool DefinitionRequired = false); | |||
5979 | ||||
5980 | /// Mark the exception specifications of all virtual member functions | |||
5981 | /// in the given class as needed. | |||
5982 | void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, | |||
5983 | const CXXRecordDecl *RD); | |||
5984 | ||||
5985 | /// MarkVirtualMembersReferenced - Will mark all members of the given | |||
5986 | /// CXXRecordDecl referenced. | |||
5987 | void MarkVirtualMembersReferenced(SourceLocation Loc, | |||
5988 | const CXXRecordDecl *RD); | |||
5989 | ||||
5990 | /// Define all of the vtables that have been used in this | |||
5991 | /// translation unit and reference any virtual members used by those | |||
5992 | /// vtables. | |||
5993 | /// | |||
5994 | /// \returns true if any work was done, false otherwise. | |||
5995 | bool DefineUsedVTables(); | |||
5996 | ||||
5997 | void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); | |||
5998 | ||||
5999 | void ActOnMemInitializers(Decl *ConstructorDecl, | |||
6000 | SourceLocation ColonLoc, | |||
6001 | ArrayRef<CXXCtorInitializer*> MemInits, | |||
6002 | bool AnyErrors); | |||
6003 | ||||
6004 | /// Check class-level dllimport/dllexport attribute. The caller must | |||
6005 | /// ensure that referenceDLLExportedClassMethods is called some point later | |||
6006 | /// when all outer classes of Class are complete. | |||
6007 | void checkClassLevelDLLAttribute(CXXRecordDecl *Class); | |||
6008 | void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); | |||
6009 | ||||
6010 | void referenceDLLExportedClassMethods(); | |||
6011 | ||||
6012 | void propagateDLLAttrToBaseClassTemplate( | |||
6013 | CXXRecordDecl *Class, Attr *ClassAttr, | |||
6014 | ClassTemplateSpecializationDecl *BaseTemplateSpec, | |||
6015 | SourceLocation BaseLoc); | |||
6016 | ||||
6017 | void CheckCompletedCXXClass(CXXRecordDecl *Record); | |||
6018 | ||||
6019 | /// Check that the C++ class annoated with "trivial_abi" satisfies all the | |||
6020 | /// conditions that are needed for the attribute to have an effect. | |||
6021 | void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); | |||
6022 | ||||
6023 | void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, | |||
6024 | Decl *TagDecl, SourceLocation LBrac, | |||
6025 | SourceLocation RBrac, | |||
6026 | const ParsedAttributesView &AttrList); | |||
6027 | void ActOnFinishCXXMemberDecls(); | |||
6028 | void ActOnFinishCXXNonNestedClass(Decl *D); | |||
6029 | ||||
6030 | void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); | |||
6031 | unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); | |||
6032 | void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); | |||
6033 | void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); | |||
6034 | void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); | |||
6035 | void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); | |||
6036 | void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); | |||
6037 | void ActOnFinishDelayedMemberInitializers(Decl *Record); | |||
6038 | void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, | |||
6039 | CachedTokens &Toks); | |||
6040 | void UnmarkAsLateParsedTemplate(FunctionDecl *FD); | |||
6041 | bool IsInsideALocalClassWithinATemplateFunction(); | |||
6042 | ||||
6043 | Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, | |||
6044 | Expr *AssertExpr, | |||
6045 | Expr *AssertMessageExpr, | |||
6046 | SourceLocation RParenLoc); | |||
6047 | Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, | |||
6048 | Expr *AssertExpr, | |||
6049 | StringLiteral *AssertMessageExpr, | |||
6050 | SourceLocation RParenLoc, | |||
6051 | bool Failed); | |||
6052 | ||||
6053 | FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, | |||
6054 | SourceLocation FriendLoc, | |||
6055 | TypeSourceInfo *TSInfo); | |||
6056 | Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, | |||
6057 | MultiTemplateParamsArg TemplateParams); | |||
6058 | NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, | |||
6059 | MultiTemplateParamsArg TemplateParams); | |||
6060 | ||||
6061 | QualType CheckConstructorDeclarator(Declarator &D, QualType R, | |||
6062 | StorageClass& SC); | |||
6063 | void CheckConstructor(CXXConstructorDecl *Constructor); | |||
6064 | QualType CheckDestructorDeclarator(Declarator &D, QualType R, | |||
6065 | StorageClass& SC); | |||
6066 | bool CheckDestructor(CXXDestructorDecl *Destructor); | |||
6067 | void CheckConversionDeclarator(Declarator &D, QualType &R, | |||
6068 | StorageClass& SC); | |||
6069 | Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); | |||
6070 | void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, | |||
6071 | StorageClass &SC); | |||
6072 | void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); | |||
6073 | ||||
6074 | void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); | |||
6075 | void CheckDelayedMemberExceptionSpecs(); | |||
6076 | ||||
6077 | //===--------------------------------------------------------------------===// | |||
6078 | // C++ Derived Classes | |||
6079 | // | |||
6080 | ||||
6081 | /// ActOnBaseSpecifier - Parsed a base specifier | |||
6082 | CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, | |||
6083 | SourceRange SpecifierRange, | |||
6084 | bool Virtual, AccessSpecifier Access, | |||
6085 | TypeSourceInfo *TInfo, | |||
6086 | SourceLocation EllipsisLoc); | |||
6087 | ||||
6088 | BaseResult ActOnBaseSpecifier(Decl *classdecl, | |||
6089 | SourceRange SpecifierRange, | |||
6090 | ParsedAttributes &Attrs, | |||
6091 | bool Virtual, AccessSpecifier Access, | |||
6092 | ParsedType basetype, | |||
6093 | SourceLocation BaseLoc, | |||
6094 | SourceLocation EllipsisLoc); | |||
6095 | ||||
6096 | bool AttachBaseSpecifiers(CXXRecordDecl *Class, | |||
6097 | MutableArrayRef<CXXBaseSpecifier *> Bases); | |||
6098 | void ActOnBaseSpecifiers(Decl *ClassDecl, | |||
6099 | MutableArrayRef<CXXBaseSpecifier *> Bases); | |||
6100 | ||||
6101 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); | |||
6102 | bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, | |||
6103 | CXXBasePaths &Paths); | |||
6104 | ||||
6105 | // FIXME: I don't like this name. | |||
6106 | void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); | |||
6107 | ||||
6108 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, | |||
6109 | SourceLocation Loc, SourceRange Range, | |||
6110 | CXXCastPath *BasePath = nullptr, | |||
6111 | bool IgnoreAccess = false); | |||
6112 | bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, | |||
6113 | unsigned InaccessibleBaseID, | |||
6114 | unsigned AmbigiousBaseConvID, | |||
6115 | SourceLocation Loc, SourceRange Range, | |||
6116 | DeclarationName Name, | |||
6117 | CXXCastPath *BasePath, | |||
6118 | bool IgnoreAccess = false); | |||
6119 | ||||
6120 | std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); | |||
6121 | ||||
6122 | bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, | |||
6123 | const CXXMethodDecl *Old); | |||
6124 | ||||
6125 | /// CheckOverridingFunctionReturnType - Checks whether the return types are | |||
6126 | /// covariant, according to C++ [class.virtual]p5. | |||
6127 | bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, | |||
6128 | const CXXMethodDecl *Old); | |||
6129 | ||||
6130 | /// CheckOverridingFunctionExceptionSpec - Checks whether the exception | |||
6131 | /// spec is a subset of base spec. | |||
6132 | bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, | |||
6133 | const CXXMethodDecl *Old); | |||
6134 | ||||
6135 | bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); | |||
6136 | ||||
6137 | /// CheckOverrideControl - Check C++11 override control semantics. | |||
6138 | void CheckOverrideControl(NamedDecl *D); | |||
6139 | ||||
6140 | /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was | |||
6141 | /// not used in the declaration of an overriding method. | |||
6142 | void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); | |||
6143 | ||||
6144 | /// CheckForFunctionMarkedFinal - Checks whether a virtual member function | |||
6145 | /// overrides a virtual member function marked 'final', according to | |||
6146 | /// C++11 [class.virtual]p4. | |||
6147 | bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, | |||
6148 | const CXXMethodDecl *Old); | |||
6149 | ||||
6150 | ||||
6151 | //===--------------------------------------------------------------------===// | |||
6152 | // C++ Access Control | |||
6153 | // | |||
6154 | ||||
6155 | enum AccessResult { | |||
6156 | AR_accessible, | |||
6157 | AR_inaccessible, | |||
6158 | AR_dependent, | |||
6159 | AR_delayed | |||
6160 | }; | |||
6161 | ||||
6162 | bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, | |||
6163 | NamedDecl *PrevMemberDecl, | |||
6164 | AccessSpecifier LexicalAS); | |||
6165 | ||||
6166 | AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, | |||
6167 | DeclAccessPair FoundDecl); | |||
6168 | AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, | |||
6169 | DeclAccessPair FoundDecl); | |||
6170 | AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, | |||
6171 | SourceRange PlacementRange, | |||
6172 | CXXRecordDecl *NamingClass, | |||
6173 | DeclAccessPair FoundDecl, | |||
6174 | bool Diagnose = true); | |||
6175 | AccessResult CheckConstructorAccess(SourceLocation Loc, | |||
6176 | CXXConstructorDecl *D, | |||
6177 | DeclAccessPair FoundDecl, | |||
6178 | const InitializedEntity &Entity, | |||
6179 | bool IsCopyBindingRefToTemp = false); | |||
6180 | AccessResult CheckConstructorAccess(SourceLocation Loc, | |||
6181 | CXXConstructorDecl *D, | |||
6182 | DeclAccessPair FoundDecl, | |||
6183 | const InitializedEntity &Entity, | |||
6184 | const PartialDiagnostic &PDiag); | |||
6185 | AccessResult CheckDestructorAccess(SourceLocation Loc, | |||
6186 | CXXDestructorDecl *Dtor, | |||
6187 | const PartialDiagnostic &PDiag, | |||
6188 | QualType objectType = QualType()); | |||
6189 | AccessResult CheckFriendAccess(NamedDecl *D); | |||
6190 | AccessResult CheckMemberAccess(SourceLocation UseLoc, | |||
6191 | CXXRecordDecl *NamingClass, | |||
6192 | DeclAccessPair Found); | |||
6193 | AccessResult | |||
6194 | CheckStructuredBindingMemberAccess(SourceLocation UseLoc, | |||
6195 | CXXRecordDecl *DecomposedClass, | |||
6196 | DeclAccessPair Field); | |||
6197 | AccessResult CheckMemberOperatorAccess(SourceLocation Loc, | |||
6198 | Expr *ObjectExpr, | |||
6199 | Expr *ArgExpr, | |||
6200 | DeclAccessPair FoundDecl); | |||
6201 | AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, | |||
6202 | DeclAccessPair FoundDecl); | |||
6203 | AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, | |||
6204 | QualType Base, QualType Derived, | |||
6205 | const CXXBasePath &Path, | |||
6206 | unsigned DiagID, | |||
6207 | bool ForceCheck = false, | |||
6208 | bool ForceUnprivileged = false); | |||
6209 | void CheckLookupAccess(const LookupResult &R); | |||
6210 | bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, | |||
6211 | QualType BaseType); | |||
6212 | bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, | |||
6213 | AccessSpecifier access, | |||
6214 | QualType objectType); | |||
6215 | ||||
6216 | void HandleDependentAccessCheck(const DependentDiagnostic &DD, | |||
6217 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
6218 | void PerformDependentDiagnostics(const DeclContext *Pattern, | |||
6219 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
6220 | ||||
6221 | void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); | |||
6222 | ||||
6223 | /// When true, access checking violations are treated as SFINAE | |||
6224 | /// failures rather than hard errors. | |||
6225 | bool AccessCheckingSFINAE; | |||
6226 | ||||
6227 | enum AbstractDiagSelID { | |||
6228 | AbstractNone = -1, | |||
6229 | AbstractReturnType, | |||
6230 | AbstractParamType, | |||
6231 | AbstractVariableType, | |||
6232 | AbstractFieldType, | |||
6233 | AbstractIvarType, | |||
6234 | AbstractSynthesizedIvarType, | |||
6235 | AbstractArrayType | |||
6236 | }; | |||
6237 | ||||
6238 | bool isAbstractType(SourceLocation Loc, QualType T); | |||
6239 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, | |||
6240 | TypeDiagnoser &Diagnoser); | |||
6241 | template <typename... Ts> | |||
6242 | bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, | |||
6243 | const Ts &...Args) { | |||
6244 | BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); | |||
6245 | return RequireNonAbstractType(Loc, T, Diagnoser); | |||
6246 | } | |||
6247 | ||||
6248 | void DiagnoseAbstractType(const CXXRecordDecl *RD); | |||
6249 | ||||
6250 | //===--------------------------------------------------------------------===// | |||
6251 | // C++ Overloaded Operators [C++ 13.5] | |||
6252 | // | |||
6253 | ||||
6254 | bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); | |||
6255 | ||||
6256 | bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); | |||
6257 | ||||
6258 | //===--------------------------------------------------------------------===// | |||
6259 | // C++ Templates [C++ 14] | |||
6260 | // | |||
6261 | void FilterAcceptableTemplateNames(LookupResult &R, | |||
6262 | bool AllowFunctionTemplates = true, | |||
6263 | bool AllowDependent = true); | |||
6264 | bool hasAnyAcceptableTemplateNames(LookupResult &R, | |||
6265 | bool AllowFunctionTemplates = true, | |||
6266 | bool AllowDependent = true, | |||
6267 | bool AllowNonTemplateFunctions = false); | |||
6268 | /// Try to interpret the lookup result D as a template-name. | |||
6269 | /// | |||
6270 | /// \param D A declaration found by name lookup. | |||
6271 | /// \param AllowFunctionTemplates Whether function templates should be | |||
6272 | /// considered valid results. | |||
6273 | /// \param AllowDependent Whether unresolved using declarations (that might | |||
6274 | /// name templates) should be considered valid results. | |||
6275 | NamedDecl *getAsTemplateNameDecl(NamedDecl *D, | |||
6276 | bool AllowFunctionTemplates = true, | |||
6277 | bool AllowDependent = true); | |||
6278 | ||||
6279 | enum class AssumedTemplateKind { | |||
6280 | /// This is not assumed to be a template name. | |||
6281 | None, | |||
6282 | /// This is assumed to be a template name because lookup found nothing. | |||
6283 | FoundNothing, | |||
6284 | /// This is assumed to be a template name because lookup found one or more | |||
6285 | /// functions (but no function templates). | |||
6286 | FoundFunctions, | |||
6287 | }; | |||
6288 | bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, | |||
6289 | QualType ObjectType, bool EnteringContext, | |||
6290 | bool &MemberOfUnknownSpecialization, | |||
6291 | SourceLocation TemplateKWLoc = SourceLocation(), | |||
6292 | AssumedTemplateKind *ATK = nullptr); | |||
6293 | ||||
6294 | TemplateNameKind isTemplateName(Scope *S, | |||
6295 | CXXScopeSpec &SS, | |||
6296 | bool hasTemplateKeyword, | |||
6297 | const UnqualifiedId &Name, | |||
6298 | ParsedType ObjectType, | |||
6299 | bool EnteringContext, | |||
6300 | TemplateTy &Template, | |||
6301 | bool &MemberOfUnknownSpecialization); | |||
6302 | ||||
6303 | /// Try to resolve an undeclared template name as a type template. | |||
6304 | /// | |||
6305 | /// Sets II to the identifier corresponding to the template name, and updates | |||
6306 | /// Name to a corresponding (typo-corrected) type template name and TNK to | |||
6307 | /// the corresponding kind, if possible. | |||
6308 | void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, | |||
6309 | TemplateNameKind &TNK, | |||
6310 | SourceLocation NameLoc, | |||
6311 | IdentifierInfo *&II); | |||
6312 | ||||
6313 | bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, | |||
6314 | SourceLocation NameLoc, | |||
6315 | bool Diagnose = true); | |||
6316 | ||||
6317 | /// Determine whether a particular identifier might be the name in a C++1z | |||
6318 | /// deduction-guide declaration. | |||
6319 | bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, | |||
6320 | SourceLocation NameLoc, | |||
6321 | ParsedTemplateTy *Template = nullptr); | |||
6322 | ||||
6323 | bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, | |||
6324 | SourceLocation IILoc, | |||
6325 | Scope *S, | |||
6326 | const CXXScopeSpec *SS, | |||
6327 | TemplateTy &SuggestedTemplate, | |||
6328 | TemplateNameKind &SuggestedKind); | |||
6329 | ||||
6330 | bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, | |||
6331 | NamedDecl *Instantiation, | |||
6332 | bool InstantiatedFromMember, | |||
6333 | const NamedDecl *Pattern, | |||
6334 | const NamedDecl *PatternDef, | |||
6335 | TemplateSpecializationKind TSK, | |||
6336 | bool Complain = true); | |||
6337 | ||||
6338 | void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); | |||
6339 | TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); | |||
6340 | ||||
6341 | NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, | |||
6342 | SourceLocation EllipsisLoc, | |||
6343 | SourceLocation KeyLoc, | |||
6344 | IdentifierInfo *ParamName, | |||
6345 | SourceLocation ParamNameLoc, | |||
6346 | unsigned Depth, unsigned Position, | |||
6347 | SourceLocation EqualLoc, | |||
6348 | ParsedType DefaultArg); | |||
6349 | ||||
6350 | QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, | |||
6351 | SourceLocation Loc); | |||
6352 | QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); | |||
6353 | ||||
6354 | NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, | |||
6355 | unsigned Depth, | |||
6356 | unsigned Position, | |||
6357 | SourceLocation EqualLoc, | |||
6358 | Expr *DefaultArg); | |||
6359 | NamedDecl *ActOnTemplateTemplateParameter(Scope *S, | |||
6360 | SourceLocation TmpLoc, | |||
6361 | TemplateParameterList *Params, | |||
6362 | SourceLocation EllipsisLoc, | |||
6363 | IdentifierInfo *ParamName, | |||
6364 | SourceLocation ParamNameLoc, | |||
6365 | unsigned Depth, | |||
6366 | unsigned Position, | |||
6367 | SourceLocation EqualLoc, | |||
6368 | ParsedTemplateArgument DefaultArg); | |||
6369 | ||||
6370 | TemplateParameterList * | |||
6371 | ActOnTemplateParameterList(unsigned Depth, | |||
6372 | SourceLocation ExportLoc, | |||
6373 | SourceLocation TemplateLoc, | |||
6374 | SourceLocation LAngleLoc, | |||
6375 | ArrayRef<NamedDecl *> Params, | |||
6376 | SourceLocation RAngleLoc, | |||
6377 | Expr *RequiresClause); | |||
6378 | ||||
6379 | /// The context in which we are checking a template parameter list. | |||
6380 | enum TemplateParamListContext { | |||
6381 | TPC_ClassTemplate, | |||
6382 | TPC_VarTemplate, | |||
6383 | TPC_FunctionTemplate, | |||
6384 | TPC_ClassTemplateMember, | |||
6385 | TPC_FriendClassTemplate, | |||
6386 | TPC_FriendFunctionTemplate, | |||
6387 | TPC_FriendFunctionTemplateDefinition, | |||
6388 | TPC_TypeAliasTemplate | |||
6389 | }; | |||
6390 | ||||
6391 | bool CheckTemplateParameterList(TemplateParameterList *NewParams, | |||
6392 | TemplateParameterList *OldParams, | |||
6393 | TemplateParamListContext TPC, | |||
6394 | SkipBodyInfo *SkipBody = nullptr); | |||
6395 | TemplateParameterList *MatchTemplateParametersToScopeSpecifier( | |||
6396 | SourceLocation DeclStartLoc, SourceLocation DeclLoc, | |||
6397 | const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, | |||
6398 | ArrayRef<TemplateParameterList *> ParamLists, | |||
6399 | bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); | |||
6400 | ||||
6401 | DeclResult CheckClassTemplate( | |||
6402 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, | |||
6403 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, | |||
6404 | const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, | |||
6405 | AccessSpecifier AS, SourceLocation ModulePrivateLoc, | |||
6406 | SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, | |||
6407 | TemplateParameterList **OuterTemplateParamLists, | |||
6408 | SkipBodyInfo *SkipBody = nullptr); | |||
6409 | ||||
6410 | TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, | |||
6411 | QualType NTTPType, | |||
6412 | SourceLocation Loc); | |||
6413 | ||||
6414 | void translateTemplateArguments(const ASTTemplateArgsPtr &In, | |||
6415 | TemplateArgumentListInfo &Out); | |||
6416 | ||||
6417 | ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); | |||
6418 | ||||
6419 | void NoteAllFoundTemplates(TemplateName Name); | |||
6420 | ||||
6421 | QualType CheckTemplateIdType(TemplateName Template, | |||
6422 | SourceLocation TemplateLoc, | |||
6423 | TemplateArgumentListInfo &TemplateArgs); | |||
6424 | ||||
6425 | TypeResult | |||
6426 | ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, | |||
6427 | TemplateTy Template, IdentifierInfo *TemplateII, | |||
6428 | SourceLocation TemplateIILoc, SourceLocation LAngleLoc, | |||
6429 | ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, | |||
6430 | bool IsCtorOrDtorName = false, bool IsClassName = false); | |||
6431 | ||||
6432 | /// Parsed an elaborated-type-specifier that refers to a template-id, | |||
6433 | /// such as \c class T::template apply<U>. | |||
6434 | TypeResult ActOnTagTemplateIdType(TagUseKind TUK, | |||
6435 | TypeSpecifierType TagSpec, | |||
6436 | SourceLocation TagLoc, | |||
6437 | CXXScopeSpec &SS, | |||
6438 | SourceLocation TemplateKWLoc, | |||
6439 | TemplateTy TemplateD, | |||
6440 | SourceLocation TemplateLoc, | |||
6441 | SourceLocation LAngleLoc, | |||
6442 | ASTTemplateArgsPtr TemplateArgsIn, | |||
6443 | SourceLocation RAngleLoc); | |||
6444 | ||||
6445 | DeclResult ActOnVarTemplateSpecialization( | |||
6446 | Scope *S, Declarator &D, TypeSourceInfo *DI, | |||
6447 | SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, | |||
6448 | StorageClass SC, bool IsPartialSpecialization); | |||
6449 | ||||
6450 | DeclResult CheckVarTemplateId(VarTemplateDecl *Template, | |||
6451 | SourceLocation TemplateLoc, | |||
6452 | SourceLocation TemplateNameLoc, | |||
6453 | const TemplateArgumentListInfo &TemplateArgs); | |||
6454 | ||||
6455 | ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, | |||
6456 | const DeclarationNameInfo &NameInfo, | |||
6457 | VarTemplateDecl *Template, | |||
6458 | SourceLocation TemplateLoc, | |||
6459 | const TemplateArgumentListInfo *TemplateArgs); | |||
6460 | ||||
6461 | void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); | |||
6462 | ||||
6463 | ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, | |||
6464 | SourceLocation TemplateKWLoc, | |||
6465 | LookupResult &R, | |||
6466 | bool RequiresADL, | |||
6467 | const TemplateArgumentListInfo *TemplateArgs); | |||
6468 | ||||
6469 | ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, | |||
6470 | SourceLocation TemplateKWLoc, | |||
6471 | const DeclarationNameInfo &NameInfo, | |||
6472 | const TemplateArgumentListInfo *TemplateArgs); | |||
6473 | ||||
6474 | TemplateNameKind ActOnDependentTemplateName( | |||
6475 | Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, | |||
6476 | const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, | |||
6477 | TemplateTy &Template, bool AllowInjectedClassName = false); | |||
6478 | ||||
6479 | DeclResult ActOnClassTemplateSpecialization( | |||
6480 | Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, | |||
6481 | SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, | |||
6482 | const ParsedAttributesView &Attr, | |||
6483 | MultiTemplateParamsArg TemplateParameterLists, | |||
6484 | SkipBodyInfo *SkipBody = nullptr); | |||
6485 | ||||
6486 | bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, | |||
6487 | TemplateDecl *PrimaryTemplate, | |||
6488 | unsigned NumExplicitArgs, | |||
6489 | ArrayRef<TemplateArgument> Args); | |||
6490 | void CheckTemplatePartialSpecialization( | |||
6491 | ClassTemplatePartialSpecializationDecl *Partial); | |||
6492 | void CheckTemplatePartialSpecialization( | |||
6493 | VarTemplatePartialSpecializationDecl *Partial); | |||
6494 | ||||
6495 | Decl *ActOnTemplateDeclarator(Scope *S, | |||
6496 | MultiTemplateParamsArg TemplateParameterLists, | |||
6497 | Declarator &D); | |||
6498 | ||||
6499 | bool | |||
6500 | CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, | |||
6501 | TemplateSpecializationKind NewTSK, | |||
6502 | NamedDecl *PrevDecl, | |||
6503 | TemplateSpecializationKind PrevTSK, | |||
6504 | SourceLocation PrevPtOfInstantiation, | |||
6505 | bool &SuppressNew); | |||
6506 | ||||
6507 | bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, | |||
6508 | const TemplateArgumentListInfo &ExplicitTemplateArgs, | |||
6509 | LookupResult &Previous); | |||
6510 | ||||
6511 | bool CheckFunctionTemplateSpecialization( | |||
6512 | FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
6513 | LookupResult &Previous, bool QualifiedFriend = false); | |||
6514 | bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); | |||
6515 | void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); | |||
6516 | ||||
6517 | DeclResult ActOnExplicitInstantiation( | |||
6518 | Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, | |||
6519 | unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, | |||
6520 | TemplateTy Template, SourceLocation TemplateNameLoc, | |||
6521 | SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, | |||
6522 | SourceLocation RAngleLoc, const ParsedAttributesView &Attr); | |||
6523 | ||||
6524 | DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, | |||
6525 | SourceLocation TemplateLoc, | |||
6526 | unsigned TagSpec, SourceLocation KWLoc, | |||
6527 | CXXScopeSpec &SS, IdentifierInfo *Name, | |||
6528 | SourceLocation NameLoc, | |||
6529 | const ParsedAttributesView &Attr); | |||
6530 | ||||
6531 | DeclResult ActOnExplicitInstantiation(Scope *S, | |||
6532 | SourceLocation ExternLoc, | |||
6533 | SourceLocation TemplateLoc, | |||
6534 | Declarator &D); | |||
6535 | ||||
6536 | TemplateArgumentLoc | |||
6537 | SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, | |||
6538 | SourceLocation TemplateLoc, | |||
6539 | SourceLocation RAngleLoc, | |||
6540 | Decl *Param, | |||
6541 | SmallVectorImpl<TemplateArgument> | |||
6542 | &Converted, | |||
6543 | bool &HasDefaultArg); | |||
6544 | ||||
6545 | /// Specifies the context in which a particular template | |||
6546 | /// argument is being checked. | |||
6547 | enum CheckTemplateArgumentKind { | |||
6548 | /// The template argument was specified in the code or was | |||
6549 | /// instantiated with some deduced template arguments. | |||
6550 | CTAK_Specified, | |||
6551 | ||||
6552 | /// The template argument was deduced via template argument | |||
6553 | /// deduction. | |||
6554 | CTAK_Deduced, | |||
6555 | ||||
6556 | /// The template argument was deduced from an array bound | |||
6557 | /// via template argument deduction. | |||
6558 | CTAK_DeducedFromArrayBound | |||
6559 | }; | |||
6560 | ||||
6561 | bool CheckTemplateArgument(NamedDecl *Param, | |||
6562 | TemplateArgumentLoc &Arg, | |||
6563 | NamedDecl *Template, | |||
6564 | SourceLocation TemplateLoc, | |||
6565 | SourceLocation RAngleLoc, | |||
6566 | unsigned ArgumentPackIndex, | |||
6567 | SmallVectorImpl<TemplateArgument> &Converted, | |||
6568 | CheckTemplateArgumentKind CTAK = CTAK_Specified); | |||
6569 | ||||
6570 | /// Check that the given template arguments can be be provided to | |||
6571 | /// the given template, converting the arguments along the way. | |||
6572 | /// | |||
6573 | /// \param Template The template to which the template arguments are being | |||
6574 | /// provided. | |||
6575 | /// | |||
6576 | /// \param TemplateLoc The location of the template name in the source. | |||
6577 | /// | |||
6578 | /// \param TemplateArgs The list of template arguments. If the template is | |||
6579 | /// a template template parameter, this function may extend the set of | |||
6580 | /// template arguments to also include substituted, defaulted template | |||
6581 | /// arguments. | |||
6582 | /// | |||
6583 | /// \param PartialTemplateArgs True if the list of template arguments is | |||
6584 | /// intentionally partial, e.g., because we're checking just the initial | |||
6585 | /// set of template arguments. | |||
6586 | /// | |||
6587 | /// \param Converted Will receive the converted, canonicalized template | |||
6588 | /// arguments. | |||
6589 | /// | |||
6590 | /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to | |||
6591 | /// contain the converted forms of the template arguments as written. | |||
6592 | /// Otherwise, \p TemplateArgs will not be modified. | |||
6593 | /// | |||
6594 | /// \returns true if an error occurred, false otherwise. | |||
6595 | bool CheckTemplateArgumentList(TemplateDecl *Template, | |||
6596 | SourceLocation TemplateLoc, | |||
6597 | TemplateArgumentListInfo &TemplateArgs, | |||
6598 | bool PartialTemplateArgs, | |||
6599 | SmallVectorImpl<TemplateArgument> &Converted, | |||
6600 | bool UpdateArgsWithConversions = true); | |||
6601 | ||||
6602 | bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, | |||
6603 | TemplateArgumentLoc &Arg, | |||
6604 | SmallVectorImpl<TemplateArgument> &Converted); | |||
6605 | ||||
6606 | bool CheckTemplateArgument(TemplateTypeParmDecl *Param, | |||
6607 | TypeSourceInfo *Arg); | |||
6608 | ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, | |||
6609 | QualType InstantiatedParamType, Expr *Arg, | |||
6610 | TemplateArgument &Converted, | |||
6611 | CheckTemplateArgumentKind CTAK = CTAK_Specified); | |||
6612 | bool CheckTemplateTemplateArgument(TemplateParameterList *Params, | |||
6613 | TemplateArgumentLoc &Arg); | |||
6614 | ||||
6615 | ExprResult | |||
6616 | BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, | |||
6617 | QualType ParamType, | |||
6618 | SourceLocation Loc); | |||
6619 | ExprResult | |||
6620 | BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, | |||
6621 | SourceLocation Loc); | |||
6622 | ||||
6623 | /// Enumeration describing how template parameter lists are compared | |||
6624 | /// for equality. | |||
6625 | enum TemplateParameterListEqualKind { | |||
6626 | /// We are matching the template parameter lists of two templates | |||
6627 | /// that might be redeclarations. | |||
6628 | /// | |||
6629 | /// \code | |||
6630 | /// template<typename T> struct X; | |||
6631 | /// template<typename T> struct X; | |||
6632 | /// \endcode | |||
6633 | TPL_TemplateMatch, | |||
6634 | ||||
6635 | /// We are matching the template parameter lists of two template | |||
6636 | /// template parameters as part of matching the template parameter lists | |||
6637 | /// of two templates that might be redeclarations. | |||
6638 | /// | |||
6639 | /// \code | |||
6640 | /// template<template<int I> class TT> struct X; | |||
6641 | /// template<template<int Value> class Other> struct X; | |||
6642 | /// \endcode | |||
6643 | TPL_TemplateTemplateParmMatch, | |||
6644 | ||||
6645 | /// We are matching the template parameter lists of a template | |||
6646 | /// template argument against the template parameter lists of a template | |||
6647 | /// template parameter. | |||
6648 | /// | |||
6649 | /// \code | |||
6650 | /// template<template<int Value> class Metafun> struct X; | |||
6651 | /// template<int Value> struct integer_c; | |||
6652 | /// X<integer_c> xic; | |||
6653 | /// \endcode | |||
6654 | TPL_TemplateTemplateArgumentMatch | |||
6655 | }; | |||
6656 | ||||
6657 | bool TemplateParameterListsAreEqual(TemplateParameterList *New, | |||
6658 | TemplateParameterList *Old, | |||
6659 | bool Complain, | |||
6660 | TemplateParameterListEqualKind Kind, | |||
6661 | SourceLocation TemplateArgLoc | |||
6662 | = SourceLocation()); | |||
6663 | ||||
6664 | bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); | |||
6665 | ||||
6666 | /// Called when the parser has parsed a C++ typename | |||
6667 | /// specifier, e.g., "typename T::type". | |||
6668 | /// | |||
6669 | /// \param S The scope in which this typename type occurs. | |||
6670 | /// \param TypenameLoc the location of the 'typename' keyword | |||
6671 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). | |||
6672 | /// \param II the identifier we're retrieving (e.g., 'type' in the example). | |||
6673 | /// \param IdLoc the location of the identifier. | |||
6674 | TypeResult | |||
6675 | ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, | |||
6676 | const CXXScopeSpec &SS, const IdentifierInfo &II, | |||
6677 | SourceLocation IdLoc); | |||
6678 | ||||
6679 | /// Called when the parser has parsed a C++ typename | |||
6680 | /// specifier that ends in a template-id, e.g., | |||
6681 | /// "typename MetaFun::template apply<T1, T2>". | |||
6682 | /// | |||
6683 | /// \param S The scope in which this typename type occurs. | |||
6684 | /// \param TypenameLoc the location of the 'typename' keyword | |||
6685 | /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). | |||
6686 | /// \param TemplateLoc the location of the 'template' keyword, if any. | |||
6687 | /// \param TemplateName The template name. | |||
6688 | /// \param TemplateII The identifier used to name the template. | |||
6689 | /// \param TemplateIILoc The location of the template name. | |||
6690 | /// \param LAngleLoc The location of the opening angle bracket ('<'). | |||
6691 | /// \param TemplateArgs The template arguments. | |||
6692 | /// \param RAngleLoc The location of the closing angle bracket ('>'). | |||
6693 | TypeResult | |||
6694 | ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, | |||
6695 | const CXXScopeSpec &SS, | |||
6696 | SourceLocation TemplateLoc, | |||
6697 | TemplateTy TemplateName, | |||
6698 | IdentifierInfo *TemplateII, | |||
6699 | SourceLocation TemplateIILoc, | |||
6700 | SourceLocation LAngleLoc, | |||
6701 | ASTTemplateArgsPtr TemplateArgs, | |||
6702 | SourceLocation RAngleLoc); | |||
6703 | ||||
6704 | QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, | |||
6705 | SourceLocation KeywordLoc, | |||
6706 | NestedNameSpecifierLoc QualifierLoc, | |||
6707 | const IdentifierInfo &II, | |||
6708 | SourceLocation IILoc); | |||
6709 | ||||
6710 | TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, | |||
6711 | SourceLocation Loc, | |||
6712 | DeclarationName Name); | |||
6713 | bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); | |||
6714 | ||||
6715 | ExprResult RebuildExprInCurrentInstantiation(Expr *E); | |||
6716 | bool RebuildTemplateParamsInCurrentInstantiation( | |||
6717 | TemplateParameterList *Params); | |||
6718 | ||||
6719 | std::string | |||
6720 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, | |||
6721 | const TemplateArgumentList &Args); | |||
6722 | ||||
6723 | std::string | |||
6724 | getTemplateArgumentBindingsText(const TemplateParameterList *Params, | |||
6725 | const TemplateArgument *Args, | |||
6726 | unsigned NumArgs); | |||
6727 | ||||
6728 | //===--------------------------------------------------------------------===// | |||
6729 | // C++ Variadic Templates (C++0x [temp.variadic]) | |||
6730 | //===--------------------------------------------------------------------===// | |||
6731 | ||||
6732 | /// Determine whether an unexpanded parameter pack might be permitted in this | |||
6733 | /// location. Useful for error recovery. | |||
6734 | bool isUnexpandedParameterPackPermitted(); | |||
6735 | ||||
6736 | /// The context in which an unexpanded parameter pack is | |||
6737 | /// being diagnosed. | |||
6738 | /// | |||
6739 | /// Note that the values of this enumeration line up with the first | |||
6740 | /// argument to the \c err_unexpanded_parameter_pack diagnostic. | |||
6741 | enum UnexpandedParameterPackContext { | |||
6742 | /// An arbitrary expression. | |||
6743 | UPPC_Expression = 0, | |||
6744 | ||||
6745 | /// The base type of a class type. | |||
6746 | UPPC_BaseType, | |||
6747 | ||||
6748 | /// The type of an arbitrary declaration. | |||
6749 | UPPC_DeclarationType, | |||
6750 | ||||
6751 | /// The type of a data member. | |||
6752 | UPPC_DataMemberType, | |||
6753 | ||||
6754 | /// The size of a bit-field. | |||
6755 | UPPC_BitFieldWidth, | |||
6756 | ||||
6757 | /// The expression in a static assertion. | |||
6758 | UPPC_StaticAssertExpression, | |||
6759 | ||||
6760 | /// The fixed underlying type of an enumeration. | |||
6761 | UPPC_FixedUnderlyingType, | |||
6762 | ||||
6763 | /// The enumerator value. | |||
6764 | UPPC_EnumeratorValue, | |||
6765 | ||||
6766 | /// A using declaration. | |||
6767 | UPPC_UsingDeclaration, | |||
6768 | ||||
6769 | /// A friend declaration. | |||
6770 | UPPC_FriendDeclaration, | |||
6771 | ||||
6772 | /// A declaration qualifier. | |||
6773 | UPPC_DeclarationQualifier, | |||
6774 | ||||
6775 | /// An initializer. | |||
6776 | UPPC_Initializer, | |||
6777 | ||||
6778 | /// A default argument. | |||
6779 | UPPC_DefaultArgument, | |||
6780 | ||||
6781 | /// The type of a non-type template parameter. | |||
6782 | UPPC_NonTypeTemplateParameterType, | |||
6783 | ||||
6784 | /// The type of an exception. | |||
6785 | UPPC_ExceptionType, | |||
6786 | ||||
6787 | /// Partial specialization. | |||
6788 | UPPC_PartialSpecialization, | |||
6789 | ||||
6790 | /// Microsoft __if_exists. | |||
6791 | UPPC_IfExists, | |||
6792 | ||||
6793 | /// Microsoft __if_not_exists. | |||
6794 | UPPC_IfNotExists, | |||
6795 | ||||
6796 | /// Lambda expression. | |||
6797 | UPPC_Lambda, | |||
6798 | ||||
6799 | /// Block expression, | |||
6800 | UPPC_Block | |||
6801 | }; | |||
6802 | ||||
6803 | /// Diagnose unexpanded parameter packs. | |||
6804 | /// | |||
6805 | /// \param Loc The location at which we should emit the diagnostic. | |||
6806 | /// | |||
6807 | /// \param UPPC The context in which we are diagnosing unexpanded | |||
6808 | /// parameter packs. | |||
6809 | /// | |||
6810 | /// \param Unexpanded the set of unexpanded parameter packs. | |||
6811 | /// | |||
6812 | /// \returns true if an error occurred, false otherwise. | |||
6813 | bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, | |||
6814 | UnexpandedParameterPackContext UPPC, | |||
6815 | ArrayRef<UnexpandedParameterPack> Unexpanded); | |||
6816 | ||||
6817 | /// If the given type contains an unexpanded parameter pack, | |||
6818 | /// diagnose the error. | |||
6819 | /// | |||
6820 | /// \param Loc The source location where a diagnostc should be emitted. | |||
6821 | /// | |||
6822 | /// \param T The type that is being checked for unexpanded parameter | |||
6823 | /// packs. | |||
6824 | /// | |||
6825 | /// \returns true if an error occurred, false otherwise. | |||
6826 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, | |||
6827 | UnexpandedParameterPackContext UPPC); | |||
6828 | ||||
6829 | /// If the given expression contains an unexpanded parameter | |||
6830 | /// pack, diagnose the error. | |||
6831 | /// | |||
6832 | /// \param E The expression that is being checked for unexpanded | |||
6833 | /// parameter packs. | |||
6834 | /// | |||
6835 | /// \returns true if an error occurred, false otherwise. | |||
6836 | bool DiagnoseUnexpandedParameterPack(Expr *E, | |||
6837 | UnexpandedParameterPackContext UPPC = UPPC_Expression); | |||
6838 | ||||
6839 | /// If the given nested-name-specifier contains an unexpanded | |||
6840 | /// parameter pack, diagnose the error. | |||
6841 | /// | |||
6842 | /// \param SS The nested-name-specifier that is being checked for | |||
6843 | /// unexpanded parameter packs. | |||
6844 | /// | |||
6845 | /// \returns true if an error occurred, false otherwise. | |||
6846 | bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, | |||
6847 | UnexpandedParameterPackContext UPPC); | |||
6848 | ||||
6849 | /// If the given name contains an unexpanded parameter pack, | |||
6850 | /// diagnose the error. | |||
6851 | /// | |||
6852 | /// \param NameInfo The name (with source location information) that | |||
6853 | /// is being checked for unexpanded parameter packs. | |||
6854 | /// | |||
6855 | /// \returns true if an error occurred, false otherwise. | |||
6856 | bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, | |||
6857 | UnexpandedParameterPackContext UPPC); | |||
6858 | ||||
6859 | /// If the given template name contains an unexpanded parameter pack, | |||
6860 | /// diagnose the error. | |||
6861 | /// | |||
6862 | /// \param Loc The location of the template name. | |||
6863 | /// | |||
6864 | /// \param Template The template name that is being checked for unexpanded | |||
6865 | /// parameter packs. | |||
6866 | /// | |||
6867 | /// \returns true if an error occurred, false otherwise. | |||
6868 | bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, | |||
6869 | TemplateName Template, | |||
6870 | UnexpandedParameterPackContext UPPC); | |||
6871 | ||||
6872 | /// If the given template argument contains an unexpanded parameter | |||
6873 | /// pack, diagnose the error. | |||
6874 | /// | |||
6875 | /// \param Arg The template argument that is being checked for unexpanded | |||
6876 | /// parameter packs. | |||
6877 | /// | |||
6878 | /// \returns true if an error occurred, false otherwise. | |||
6879 | bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, | |||
6880 | UnexpandedParameterPackContext UPPC); | |||
6881 | ||||
6882 | /// Collect the set of unexpanded parameter packs within the given | |||
6883 | /// template argument. | |||
6884 | /// | |||
6885 | /// \param Arg The template argument that will be traversed to find | |||
6886 | /// unexpanded parameter packs. | |||
6887 | void collectUnexpandedParameterPacks(TemplateArgument Arg, | |||
6888 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); | |||
6889 | ||||
6890 | /// Collect the set of unexpanded parameter packs within the given | |||
6891 | /// template argument. | |||
6892 | /// | |||
6893 | /// \param Arg The template argument that will be traversed to find | |||
6894 | /// unexpanded parameter packs. | |||
6895 | void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, | |||
6896 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); | |||
6897 | ||||
6898 | /// Collect the set of unexpanded parameter packs within the given | |||
6899 | /// type. | |||
6900 | /// | |||
6901 | /// \param T The type that will be traversed to find | |||
6902 | /// unexpanded parameter packs. | |||
6903 | void collectUnexpandedParameterPacks(QualType T, | |||
6904 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); | |||
6905 | ||||
6906 | /// Collect the set of unexpanded parameter packs within the given | |||
6907 | /// type. | |||
6908 | /// | |||
6909 | /// \param TL The type that will be traversed to find | |||
6910 | /// unexpanded parameter packs. | |||
6911 | void collectUnexpandedParameterPacks(TypeLoc TL, | |||
6912 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); | |||
6913 | ||||
6914 | /// Collect the set of unexpanded parameter packs within the given | |||
6915 | /// nested-name-specifier. | |||
6916 | /// | |||
6917 | /// \param NNS The nested-name-specifier that will be traversed to find | |||
6918 | /// unexpanded parameter packs. | |||
6919 | void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, | |||
6920 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); | |||
6921 | ||||
6922 | /// Collect the set of unexpanded parameter packs within the given | |||
6923 | /// name. | |||
6924 | /// | |||
6925 | /// \param NameInfo The name that will be traversed to find | |||
6926 | /// unexpanded parameter packs. | |||
6927 | void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, | |||
6928 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); | |||
6929 | ||||
6930 | /// Invoked when parsing a template argument followed by an | |||
6931 | /// ellipsis, which creates a pack expansion. | |||
6932 | /// | |||
6933 | /// \param Arg The template argument preceding the ellipsis, which | |||
6934 | /// may already be invalid. | |||
6935 | /// | |||
6936 | /// \param EllipsisLoc The location of the ellipsis. | |||
6937 | ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, | |||
6938 | SourceLocation EllipsisLoc); | |||
6939 | ||||
6940 | /// Invoked when parsing a type followed by an ellipsis, which | |||
6941 | /// creates a pack expansion. | |||
6942 | /// | |||
6943 | /// \param Type The type preceding the ellipsis, which will become | |||
6944 | /// the pattern of the pack expansion. | |||
6945 | /// | |||
6946 | /// \param EllipsisLoc The location of the ellipsis. | |||
6947 | TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); | |||
6948 | ||||
6949 | /// Construct a pack expansion type from the pattern of the pack | |||
6950 | /// expansion. | |||
6951 | TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, | |||
6952 | SourceLocation EllipsisLoc, | |||
6953 | Optional<unsigned> NumExpansions); | |||
6954 | ||||
6955 | /// Construct a pack expansion type from the pattern of the pack | |||
6956 | /// expansion. | |||
6957 | QualType CheckPackExpansion(QualType Pattern, | |||
6958 | SourceRange PatternRange, | |||
6959 | SourceLocation EllipsisLoc, | |||
6960 | Optional<unsigned> NumExpansions); | |||
6961 | ||||
6962 | /// Invoked when parsing an expression followed by an ellipsis, which | |||
6963 | /// creates a pack expansion. | |||
6964 | /// | |||
6965 | /// \param Pattern The expression preceding the ellipsis, which will become | |||
6966 | /// the pattern of the pack expansion. | |||
6967 | /// | |||
6968 | /// \param EllipsisLoc The location of the ellipsis. | |||
6969 | ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); | |||
6970 | ||||
6971 | /// Invoked when parsing an expression followed by an ellipsis, which | |||
6972 | /// creates a pack expansion. | |||
6973 | /// | |||
6974 | /// \param Pattern The expression preceding the ellipsis, which will become | |||
6975 | /// the pattern of the pack expansion. | |||
6976 | /// | |||
6977 | /// \param EllipsisLoc The location of the ellipsis. | |||
6978 | ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, | |||
6979 | Optional<unsigned> NumExpansions); | |||
6980 | ||||
6981 | /// Determine whether we could expand a pack expansion with the | |||
6982 | /// given set of parameter packs into separate arguments by repeatedly | |||
6983 | /// transforming the pattern. | |||
6984 | /// | |||
6985 | /// \param EllipsisLoc The location of the ellipsis that identifies the | |||
6986 | /// pack expansion. | |||
6987 | /// | |||
6988 | /// \param PatternRange The source range that covers the entire pattern of | |||
6989 | /// the pack expansion. | |||
6990 | /// | |||
6991 | /// \param Unexpanded The set of unexpanded parameter packs within the | |||
6992 | /// pattern. | |||
6993 | /// | |||
6994 | /// \param ShouldExpand Will be set to \c true if the transformer should | |||
6995 | /// expand the corresponding pack expansions into separate arguments. When | |||
6996 | /// set, \c NumExpansions must also be set. | |||
6997 | /// | |||
6998 | /// \param RetainExpansion Whether the caller should add an unexpanded | |||
6999 | /// pack expansion after all of the expanded arguments. This is used | |||
7000 | /// when extending explicitly-specified template argument packs per | |||
7001 | /// C++0x [temp.arg.explicit]p9. | |||
7002 | /// | |||
7003 | /// \param NumExpansions The number of separate arguments that will be in | |||
7004 | /// the expanded form of the corresponding pack expansion. This is both an | |||
7005 | /// input and an output parameter, which can be set by the caller if the | |||
7006 | /// number of expansions is known a priori (e.g., due to a prior substitution) | |||
7007 | /// and will be set by the callee when the number of expansions is known. | |||
7008 | /// The callee must set this value when \c ShouldExpand is \c true; it may | |||
7009 | /// set this value in other cases. | |||
7010 | /// | |||
7011 | /// \returns true if an error occurred (e.g., because the parameter packs | |||
7012 | /// are to be instantiated with arguments of different lengths), false | |||
7013 | /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) | |||
7014 | /// must be set. | |||
7015 | bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, | |||
7016 | SourceRange PatternRange, | |||
7017 | ArrayRef<UnexpandedParameterPack> Unexpanded, | |||
7018 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7019 | bool &ShouldExpand, | |||
7020 | bool &RetainExpansion, | |||
7021 | Optional<unsigned> &NumExpansions); | |||
7022 | ||||
7023 | /// Determine the number of arguments in the given pack expansion | |||
7024 | /// type. | |||
7025 | /// | |||
7026 | /// This routine assumes that the number of arguments in the expansion is | |||
7027 | /// consistent across all of the unexpanded parameter packs in its pattern. | |||
7028 | /// | |||
7029 | /// Returns an empty Optional if the type can't be expanded. | |||
7030 | Optional<unsigned> getNumArgumentsInExpansion(QualType T, | |||
7031 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
7032 | ||||
7033 | /// Determine whether the given declarator contains any unexpanded | |||
7034 | /// parameter packs. | |||
7035 | /// | |||
7036 | /// This routine is used by the parser to disambiguate function declarators | |||
7037 | /// with an ellipsis prior to the ')', e.g., | |||
7038 | /// | |||
7039 | /// \code | |||
7040 | /// void f(T...); | |||
7041 | /// \endcode | |||
7042 | /// | |||
7043 | /// To determine whether we have an (unnamed) function parameter pack or | |||
7044 | /// a variadic function. | |||
7045 | /// | |||
7046 | /// \returns true if the declarator contains any unexpanded parameter packs, | |||
7047 | /// false otherwise. | |||
7048 | bool containsUnexpandedParameterPacks(Declarator &D); | |||
7049 | ||||
7050 | /// Returns the pattern of the pack expansion for a template argument. | |||
7051 | /// | |||
7052 | /// \param OrigLoc The template argument to expand. | |||
7053 | /// | |||
7054 | /// \param Ellipsis Will be set to the location of the ellipsis. | |||
7055 | /// | |||
7056 | /// \param NumExpansions Will be set to the number of expansions that will | |||
7057 | /// be generated from this pack expansion, if known a priori. | |||
7058 | TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( | |||
7059 | TemplateArgumentLoc OrigLoc, | |||
7060 | SourceLocation &Ellipsis, | |||
7061 | Optional<unsigned> &NumExpansions) const; | |||
7062 | ||||
7063 | /// Given a template argument that contains an unexpanded parameter pack, but | |||
7064 | /// which has already been substituted, attempt to determine the number of | |||
7065 | /// elements that will be produced once this argument is fully-expanded. | |||
7066 | /// | |||
7067 | /// This is intended for use when transforming 'sizeof...(Arg)' in order to | |||
7068 | /// avoid actually expanding the pack where possible. | |||
7069 | Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); | |||
7070 | ||||
7071 | //===--------------------------------------------------------------------===// | |||
7072 | // C++ Template Argument Deduction (C++ [temp.deduct]) | |||
7073 | //===--------------------------------------------------------------------===// | |||
7074 | ||||
7075 | /// Adjust the type \p ArgFunctionType to match the calling convention, | |||
7076 | /// noreturn, and optionally the exception specification of \p FunctionType. | |||
7077 | /// Deduction often wants to ignore these properties when matching function | |||
7078 | /// types. | |||
7079 | QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, | |||
7080 | bool AdjustExceptionSpec = false); | |||
7081 | ||||
7082 | /// Describes the result of template argument deduction. | |||
7083 | /// | |||
7084 | /// The TemplateDeductionResult enumeration describes the result of | |||
7085 | /// template argument deduction, as returned from | |||
7086 | /// DeduceTemplateArguments(). The separate TemplateDeductionInfo | |||
7087 | /// structure provides additional information about the results of | |||
7088 | /// template argument deduction, e.g., the deduced template argument | |||
7089 | /// list (if successful) or the specific template parameters or | |||
7090 | /// deduced arguments that were involved in the failure. | |||
7091 | enum TemplateDeductionResult { | |||
7092 | /// Template argument deduction was successful. | |||
7093 | TDK_Success = 0, | |||
7094 | /// The declaration was invalid; do nothing. | |||
7095 | TDK_Invalid, | |||
7096 | /// Template argument deduction exceeded the maximum template | |||
7097 | /// instantiation depth (which has already been diagnosed). | |||
7098 | TDK_InstantiationDepth, | |||
7099 | /// Template argument deduction did not deduce a value | |||
7100 | /// for every template parameter. | |||
7101 | TDK_Incomplete, | |||
7102 | /// Template argument deduction did not deduce a value for every | |||
7103 | /// expansion of an expanded template parameter pack. | |||
7104 | TDK_IncompletePack, | |||
7105 | /// Template argument deduction produced inconsistent | |||
7106 | /// deduced values for the given template parameter. | |||
7107 | TDK_Inconsistent, | |||
7108 | /// Template argument deduction failed due to inconsistent | |||
7109 | /// cv-qualifiers on a template parameter type that would | |||
7110 | /// otherwise be deduced, e.g., we tried to deduce T in "const T" | |||
7111 | /// but were given a non-const "X". | |||
7112 | TDK_Underqualified, | |||
7113 | /// Substitution of the deduced template argument values | |||
7114 | /// resulted in an error. | |||
7115 | TDK_SubstitutionFailure, | |||
7116 | /// After substituting deduced template arguments, a dependent | |||
7117 | /// parameter type did not match the corresponding argument. | |||
7118 | TDK_DeducedMismatch, | |||
7119 | /// After substituting deduced template arguments, an element of | |||
7120 | /// a dependent parameter type did not match the corresponding element | |||
7121 | /// of the corresponding argument (when deducing from an initializer list). | |||
7122 | TDK_DeducedMismatchNested, | |||
7123 | /// A non-depnedent component of the parameter did not match the | |||
7124 | /// corresponding component of the argument. | |||
7125 | TDK_NonDeducedMismatch, | |||
7126 | /// When performing template argument deduction for a function | |||
7127 | /// template, there were too many call arguments. | |||
7128 | TDK_TooManyArguments, | |||
7129 | /// When performing template argument deduction for a function | |||
7130 | /// template, there were too few call arguments. | |||
7131 | TDK_TooFewArguments, | |||
7132 | /// The explicitly-specified template arguments were not valid | |||
7133 | /// template arguments for the given template. | |||
7134 | TDK_InvalidExplicitArguments, | |||
7135 | /// Checking non-dependent argument conversions failed. | |||
7136 | TDK_NonDependentConversionFailure, | |||
7137 | /// Deduction failed; that's all we know. | |||
7138 | TDK_MiscellaneousDeductionFailure, | |||
7139 | /// CUDA Target attributes do not match. | |||
7140 | TDK_CUDATargetMismatch | |||
7141 | }; | |||
7142 | ||||
7143 | TemplateDeductionResult | |||
7144 | DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, | |||
7145 | const TemplateArgumentList &TemplateArgs, | |||
7146 | sema::TemplateDeductionInfo &Info); | |||
7147 | ||||
7148 | TemplateDeductionResult | |||
7149 | DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, | |||
7150 | const TemplateArgumentList &TemplateArgs, | |||
7151 | sema::TemplateDeductionInfo &Info); | |||
7152 | ||||
7153 | TemplateDeductionResult SubstituteExplicitTemplateArguments( | |||
7154 | FunctionTemplateDecl *FunctionTemplate, | |||
7155 | TemplateArgumentListInfo &ExplicitTemplateArgs, | |||
7156 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, | |||
7157 | SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, | |||
7158 | sema::TemplateDeductionInfo &Info); | |||
7159 | ||||
7160 | /// brief A function argument from which we performed template argument | |||
7161 | // deduction for a call. | |||
7162 | struct OriginalCallArg { | |||
7163 | OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, | |||
7164 | unsigned ArgIdx, QualType OriginalArgType) | |||
7165 | : OriginalParamType(OriginalParamType), | |||
7166 | DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), | |||
7167 | OriginalArgType(OriginalArgType) {} | |||
7168 | ||||
7169 | QualType OriginalParamType; | |||
7170 | bool DecomposedParam; | |||
7171 | unsigned ArgIdx; | |||
7172 | QualType OriginalArgType; | |||
7173 | }; | |||
7174 | ||||
7175 | TemplateDeductionResult FinishTemplateArgumentDeduction( | |||
7176 | FunctionTemplateDecl *FunctionTemplate, | |||
7177 | SmallVectorImpl<DeducedTemplateArgument> &Deduced, | |||
7178 | unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, | |||
7179 | sema::TemplateDeductionInfo &Info, | |||
7180 | SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, | |||
7181 | bool PartialOverloading = false, | |||
7182 | llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); | |||
7183 | ||||
7184 | TemplateDeductionResult DeduceTemplateArguments( | |||
7185 | FunctionTemplateDecl *FunctionTemplate, | |||
7186 | TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, | |||
7187 | FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, | |||
7188 | bool PartialOverloading, | |||
7189 | llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); | |||
7190 | ||||
7191 | TemplateDeductionResult | |||
7192 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, | |||
7193 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
7194 | QualType ArgFunctionType, | |||
7195 | FunctionDecl *&Specialization, | |||
7196 | sema::TemplateDeductionInfo &Info, | |||
7197 | bool IsAddressOfFunction = false); | |||
7198 | ||||
7199 | TemplateDeductionResult | |||
7200 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, | |||
7201 | QualType ToType, | |||
7202 | CXXConversionDecl *&Specialization, | |||
7203 | sema::TemplateDeductionInfo &Info); | |||
7204 | ||||
7205 | TemplateDeductionResult | |||
7206 | DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, | |||
7207 | TemplateArgumentListInfo *ExplicitTemplateArgs, | |||
7208 | FunctionDecl *&Specialization, | |||
7209 | sema::TemplateDeductionInfo &Info, | |||
7210 | bool IsAddressOfFunction = false); | |||
7211 | ||||
7212 | /// Substitute Replacement for \p auto in \p TypeWithAuto | |||
7213 | QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); | |||
7214 | /// Substitute Replacement for auto in TypeWithAuto | |||
7215 | TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, | |||
7216 | QualType Replacement); | |||
7217 | /// Completely replace the \c auto in \p TypeWithAuto by | |||
7218 | /// \p Replacement. This does not retain any \c auto type sugar. | |||
7219 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); | |||
7220 | ||||
7221 | /// Result type of DeduceAutoType. | |||
7222 | enum DeduceAutoResult { | |||
7223 | DAR_Succeeded, | |||
7224 | DAR_Failed, | |||
7225 | DAR_FailedAlreadyDiagnosed | |||
7226 | }; | |||
7227 | ||||
7228 | DeduceAutoResult | |||
7229 | DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, | |||
7230 | Optional<unsigned> DependentDeductionDepth = None); | |||
7231 | DeduceAutoResult | |||
7232 | DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, | |||
7233 | Optional<unsigned> DependentDeductionDepth = None); | |||
7234 | void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); | |||
7235 | bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, | |||
7236 | bool Diagnose = true); | |||
7237 | ||||
7238 | /// Declare implicit deduction guides for a class template if we've | |||
7239 | /// not already done so. | |||
7240 | void DeclareImplicitDeductionGuides(TemplateDecl *Template, | |||
7241 | SourceLocation Loc); | |||
7242 | ||||
7243 | QualType DeduceTemplateSpecializationFromInitializer( | |||
7244 | TypeSourceInfo *TInfo, const InitializedEntity &Entity, | |||
7245 | const InitializationKind &Kind, MultiExprArg Init); | |||
7246 | ||||
7247 | QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, | |||
7248 | QualType Type, TypeSourceInfo *TSI, | |||
7249 | SourceRange Range, bool DirectInit, | |||
7250 | Expr *Init); | |||
7251 | ||||
7252 | TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; | |||
7253 | ||||
7254 | bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, | |||
7255 | SourceLocation ReturnLoc, | |||
7256 | Expr *&RetExpr, AutoType *AT); | |||
7257 | ||||
7258 | FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, | |||
7259 | FunctionTemplateDecl *FT2, | |||
7260 | SourceLocation Loc, | |||
7261 | TemplatePartialOrderingContext TPOC, | |||
7262 | unsigned NumCallArguments1, | |||
7263 | unsigned NumCallArguments2); | |||
7264 | UnresolvedSetIterator | |||
7265 | getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, | |||
7266 | TemplateSpecCandidateSet &FailedCandidates, | |||
7267 | SourceLocation Loc, | |||
7268 | const PartialDiagnostic &NoneDiag, | |||
7269 | const PartialDiagnostic &AmbigDiag, | |||
7270 | const PartialDiagnostic &CandidateDiag, | |||
7271 | bool Complain = true, QualType TargetType = QualType()); | |||
7272 | ||||
7273 | ClassTemplatePartialSpecializationDecl * | |||
7274 | getMoreSpecializedPartialSpecialization( | |||
7275 | ClassTemplatePartialSpecializationDecl *PS1, | |||
7276 | ClassTemplatePartialSpecializationDecl *PS2, | |||
7277 | SourceLocation Loc); | |||
7278 | ||||
7279 | bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, | |||
7280 | sema::TemplateDeductionInfo &Info); | |||
7281 | ||||
7282 | VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( | |||
7283 | VarTemplatePartialSpecializationDecl *PS1, | |||
7284 | VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); | |||
7285 | ||||
7286 | bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, | |||
7287 | sema::TemplateDeductionInfo &Info); | |||
7288 | ||||
7289 | bool isTemplateTemplateParameterAtLeastAsSpecializedAs( | |||
7290 | TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); | |||
7291 | ||||
7292 | void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, | |||
7293 | bool OnlyDeduced, | |||
7294 | unsigned Depth, | |||
7295 | llvm::SmallBitVector &Used); | |||
7296 | void MarkDeducedTemplateParameters( | |||
7297 | const FunctionTemplateDecl *FunctionTemplate, | |||
7298 | llvm::SmallBitVector &Deduced) { | |||
7299 | return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); | |||
7300 | } | |||
7301 | static void MarkDeducedTemplateParameters(ASTContext &Ctx, | |||
7302 | const FunctionTemplateDecl *FunctionTemplate, | |||
7303 | llvm::SmallBitVector &Deduced); | |||
7304 | ||||
7305 | //===--------------------------------------------------------------------===// | |||
7306 | // C++ Template Instantiation | |||
7307 | // | |||
7308 | ||||
7309 | MultiLevelTemplateArgumentList | |||
7310 | getTemplateInstantiationArgs(NamedDecl *D, | |||
7311 | const TemplateArgumentList *Innermost = nullptr, | |||
7312 | bool RelativeToPrimary = false, | |||
7313 | const FunctionDecl *Pattern = nullptr); | |||
7314 | ||||
7315 | /// A context in which code is being synthesized (where a source location | |||
7316 | /// alone is not sufficient to identify the context). This covers template | |||
7317 | /// instantiation and various forms of implicitly-generated functions. | |||
7318 | struct CodeSynthesisContext { | |||
7319 | /// The kind of template instantiation we are performing | |||
7320 | enum SynthesisKind { | |||
7321 | /// We are instantiating a template declaration. The entity is | |||
7322 | /// the declaration we're instantiating (e.g., a CXXRecordDecl). | |||
7323 | TemplateInstantiation, | |||
7324 | ||||
7325 | /// We are instantiating a default argument for a template | |||
7326 | /// parameter. The Entity is the template parameter whose argument is | |||
7327 | /// being instantiated, the Template is the template, and the | |||
7328 | /// TemplateArgs/NumTemplateArguments provide the template arguments as | |||
7329 | /// specified. | |||
7330 | DefaultTemplateArgumentInstantiation, | |||
7331 | ||||
7332 | /// We are instantiating a default argument for a function. | |||
7333 | /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs | |||
7334 | /// provides the template arguments as specified. | |||
7335 | DefaultFunctionArgumentInstantiation, | |||
7336 | ||||
7337 | /// We are substituting explicit template arguments provided for | |||
7338 | /// a function template. The entity is a FunctionTemplateDecl. | |||
7339 | ExplicitTemplateArgumentSubstitution, | |||
7340 | ||||
7341 | /// We are substituting template argument determined as part of | |||
7342 | /// template argument deduction for either a class template | |||
7343 | /// partial specialization or a function template. The | |||
7344 | /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or | |||
7345 | /// a TemplateDecl. | |||
7346 | DeducedTemplateArgumentSubstitution, | |||
7347 | ||||
7348 | /// We are substituting prior template arguments into a new | |||
7349 | /// template parameter. The template parameter itself is either a | |||
7350 | /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. | |||
7351 | PriorTemplateArgumentSubstitution, | |||
7352 | ||||
7353 | /// We are checking the validity of a default template argument that | |||
7354 | /// has been used when naming a template-id. | |||
7355 | DefaultTemplateArgumentChecking, | |||
7356 | ||||
7357 | /// We are computing the exception specification for a defaulted special | |||
7358 | /// member function. | |||
7359 | ExceptionSpecEvaluation, | |||
7360 | ||||
7361 | /// We are instantiating the exception specification for a function | |||
7362 | /// template which was deferred until it was needed. | |||
7363 | ExceptionSpecInstantiation, | |||
7364 | ||||
7365 | /// We are declaring an implicit special member function. | |||
7366 | DeclaringSpecialMember, | |||
7367 | ||||
7368 | /// We are defining a synthesized function (such as a defaulted special | |||
7369 | /// member). | |||
7370 | DefiningSynthesizedFunction, | |||
7371 | ||||
7372 | /// Added for Template instantiation observation. | |||
7373 | /// Memoization means we are _not_ instantiating a template because | |||
7374 | /// it is already instantiated (but we entered a context where we | |||
7375 | /// would have had to if it was not already instantiated). | |||
7376 | Memoization | |||
7377 | } Kind; | |||
7378 | ||||
7379 | /// Was the enclosing context a non-instantiation SFINAE context? | |||
7380 | bool SavedInNonInstantiationSFINAEContext; | |||
7381 | ||||
7382 | /// The point of instantiation or synthesis within the source code. | |||
7383 | SourceLocation PointOfInstantiation; | |||
7384 | ||||
7385 | /// The entity that is being synthesized. | |||
7386 | Decl *Entity; | |||
7387 | ||||
7388 | /// The template (or partial specialization) in which we are | |||
7389 | /// performing the instantiation, for substitutions of prior template | |||
7390 | /// arguments. | |||
7391 | NamedDecl *Template; | |||
7392 | ||||
7393 | /// The list of template arguments we are substituting, if they | |||
7394 | /// are not part of the entity. | |||
7395 | const TemplateArgument *TemplateArgs; | |||
7396 | ||||
7397 | // FIXME: Wrap this union around more members, or perhaps store the | |||
7398 | // kind-specific members in the RAII object owning the context. | |||
7399 | union { | |||
7400 | /// The number of template arguments in TemplateArgs. | |||
7401 | unsigned NumTemplateArgs; | |||
7402 | ||||
7403 | /// The special member being declared or defined. | |||
7404 | CXXSpecialMember SpecialMember; | |||
7405 | }; | |||
7406 | ||||
7407 | ArrayRef<TemplateArgument> template_arguments() const { | |||
7408 | assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> ( 0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7408, __PRETTY_FUNCTION__)); | |||
7409 | return {TemplateArgs, NumTemplateArgs}; | |||
7410 | } | |||
7411 | ||||
7412 | /// The template deduction info object associated with the | |||
7413 | /// substitution or checking of explicit or deduced template arguments. | |||
7414 | sema::TemplateDeductionInfo *DeductionInfo; | |||
7415 | ||||
7416 | /// The source range that covers the construct that cause | |||
7417 | /// the instantiation, e.g., the template-id that causes a class | |||
7418 | /// template instantiation. | |||
7419 | SourceRange InstantiationRange; | |||
7420 | ||||
7421 | CodeSynthesisContext() | |||
7422 | : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr), | |||
7423 | TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} | |||
7424 | ||||
7425 | /// Determines whether this template is an actual instantiation | |||
7426 | /// that should be counted toward the maximum instantiation depth. | |||
7427 | bool isInstantiationRecord() const; | |||
7428 | }; | |||
7429 | ||||
7430 | /// List of active code synthesis contexts. | |||
7431 | /// | |||
7432 | /// This vector is treated as a stack. As synthesis of one entity requires | |||
7433 | /// synthesis of another, additional contexts are pushed onto the stack. | |||
7434 | SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; | |||
7435 | ||||
7436 | /// Specializations whose definitions are currently being instantiated. | |||
7437 | llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; | |||
7438 | ||||
7439 | /// Non-dependent types used in templates that have already been instantiated | |||
7440 | /// by some template instantiation. | |||
7441 | llvm::DenseSet<QualType> InstantiatedNonDependentTypes; | |||
7442 | ||||
7443 | /// Extra modules inspected when performing a lookup during a template | |||
7444 | /// instantiation. Computed lazily. | |||
7445 | SmallVector<Module*, 16> CodeSynthesisContextLookupModules; | |||
7446 | ||||
7447 | /// Cache of additional modules that should be used for name lookup | |||
7448 | /// within the current template instantiation. Computed lazily; use | |||
7449 | /// getLookupModules() to get a complete set. | |||
7450 | llvm::DenseSet<Module*> LookupModulesCache; | |||
7451 | ||||
7452 | /// Get the set of additional modules that should be checked during | |||
7453 | /// name lookup. A module and its imports become visible when instanting a | |||
7454 | /// template defined within it. | |||
7455 | llvm::DenseSet<Module*> &getLookupModules(); | |||
7456 | ||||
7457 | /// Map from the most recent declaration of a namespace to the most | |||
7458 | /// recent visible declaration of that namespace. | |||
7459 | llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; | |||
7460 | ||||
7461 | /// Whether we are in a SFINAE context that is not associated with | |||
7462 | /// template instantiation. | |||
7463 | /// | |||
7464 | /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside | |||
7465 | /// of a template instantiation or template argument deduction. | |||
7466 | bool InNonInstantiationSFINAEContext; | |||
7467 | ||||
7468 | /// The number of \p CodeSynthesisContexts that are not template | |||
7469 | /// instantiations and, therefore, should not be counted as part of the | |||
7470 | /// instantiation depth. | |||
7471 | /// | |||
7472 | /// When the instantiation depth reaches the user-configurable limit | |||
7473 | /// \p LangOptions::InstantiationDepth we will abort instantiation. | |||
7474 | // FIXME: Should we have a similar limit for other forms of synthesis? | |||
7475 | unsigned NonInstantiationEntries; | |||
7476 | ||||
7477 | /// The depth of the context stack at the point when the most recent | |||
7478 | /// error or warning was produced. | |||
7479 | /// | |||
7480 | /// This value is used to suppress printing of redundant context stacks | |||
7481 | /// when there are multiple errors or warnings in the same instantiation. | |||
7482 | // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. | |||
7483 | unsigned LastEmittedCodeSynthesisContextDepth = 0; | |||
7484 | ||||
7485 | /// The template instantiation callbacks to trace or track | |||
7486 | /// instantiations (objects can be chained). | |||
7487 | /// | |||
7488 | /// This callbacks is used to print, trace or track template | |||
7489 | /// instantiations as they are being constructed. | |||
7490 | std::vector<std::unique_ptr<TemplateInstantiationCallback>> | |||
7491 | TemplateInstCallbacks; | |||
7492 | ||||
7493 | /// The current index into pack expansion arguments that will be | |||
7494 | /// used for substitution of parameter packs. | |||
7495 | /// | |||
7496 | /// The pack expansion index will be -1 to indicate that parameter packs | |||
7497 | /// should be instantiated as themselves. Otherwise, the index specifies | |||
7498 | /// which argument within the parameter pack will be used for substitution. | |||
7499 | int ArgumentPackSubstitutionIndex; | |||
7500 | ||||
7501 | /// RAII object used to change the argument pack substitution index | |||
7502 | /// within a \c Sema object. | |||
7503 | /// | |||
7504 | /// See \c ArgumentPackSubstitutionIndex for more information. | |||
7505 | class ArgumentPackSubstitutionIndexRAII { | |||
7506 | Sema &Self; | |||
7507 | int OldSubstitutionIndex; | |||
7508 | ||||
7509 | public: | |||
7510 | ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) | |||
7511 | : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { | |||
7512 | Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; | |||
7513 | } | |||
7514 | ||||
7515 | ~ArgumentPackSubstitutionIndexRAII() { | |||
7516 | Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; | |||
7517 | } | |||
7518 | }; | |||
7519 | ||||
7520 | friend class ArgumentPackSubstitutionRAII; | |||
7521 | ||||
7522 | /// For each declaration that involved template argument deduction, the | |||
7523 | /// set of diagnostics that were suppressed during that template argument | |||
7524 | /// deduction. | |||
7525 | /// | |||
7526 | /// FIXME: Serialize this structure to the AST file. | |||
7527 | typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > | |||
7528 | SuppressedDiagnosticsMap; | |||
7529 | SuppressedDiagnosticsMap SuppressedDiagnostics; | |||
7530 | ||||
7531 | /// A stack object to be created when performing template | |||
7532 | /// instantiation. | |||
7533 | /// | |||
7534 | /// Construction of an object of type \c InstantiatingTemplate | |||
7535 | /// pushes the current instantiation onto the stack of active | |||
7536 | /// instantiations. If the size of this stack exceeds the maximum | |||
7537 | /// number of recursive template instantiations, construction | |||
7538 | /// produces an error and evaluates true. | |||
7539 | /// | |||
7540 | /// Destruction of this object will pop the named instantiation off | |||
7541 | /// the stack. | |||
7542 | struct InstantiatingTemplate { | |||
7543 | /// Note that we are instantiating a class template, | |||
7544 | /// function template, variable template, alias template, | |||
7545 | /// or a member thereof. | |||
7546 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7547 | Decl *Entity, | |||
7548 | SourceRange InstantiationRange = SourceRange()); | |||
7549 | ||||
7550 | struct ExceptionSpecification {}; | |||
7551 | /// Note that we are instantiating an exception specification | |||
7552 | /// of a function template. | |||
7553 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7554 | FunctionDecl *Entity, ExceptionSpecification, | |||
7555 | SourceRange InstantiationRange = SourceRange()); | |||
7556 | ||||
7557 | /// Note that we are instantiating a default argument in a | |||
7558 | /// template-id. | |||
7559 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7560 | TemplateParameter Param, TemplateDecl *Template, | |||
7561 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7562 | SourceRange InstantiationRange = SourceRange()); | |||
7563 | ||||
7564 | /// Note that we are substituting either explicitly-specified or | |||
7565 | /// deduced template arguments during function template argument deduction. | |||
7566 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7567 | FunctionTemplateDecl *FunctionTemplate, | |||
7568 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7569 | CodeSynthesisContext::SynthesisKind Kind, | |||
7570 | sema::TemplateDeductionInfo &DeductionInfo, | |||
7571 | SourceRange InstantiationRange = SourceRange()); | |||
7572 | ||||
7573 | /// Note that we are instantiating as part of template | |||
7574 | /// argument deduction for a class template declaration. | |||
7575 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7576 | TemplateDecl *Template, | |||
7577 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7578 | sema::TemplateDeductionInfo &DeductionInfo, | |||
7579 | SourceRange InstantiationRange = SourceRange()); | |||
7580 | ||||
7581 | /// Note that we are instantiating as part of template | |||
7582 | /// argument deduction for a class template partial | |||
7583 | /// specialization. | |||
7584 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7585 | ClassTemplatePartialSpecializationDecl *PartialSpec, | |||
7586 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7587 | sema::TemplateDeductionInfo &DeductionInfo, | |||
7588 | SourceRange InstantiationRange = SourceRange()); | |||
7589 | ||||
7590 | /// Note that we are instantiating as part of template | |||
7591 | /// argument deduction for a variable template partial | |||
7592 | /// specialization. | |||
7593 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7594 | VarTemplatePartialSpecializationDecl *PartialSpec, | |||
7595 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7596 | sema::TemplateDeductionInfo &DeductionInfo, | |||
7597 | SourceRange InstantiationRange = SourceRange()); | |||
7598 | ||||
7599 | /// Note that we are instantiating a default argument for a function | |||
7600 | /// parameter. | |||
7601 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7602 | ParmVarDecl *Param, | |||
7603 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7604 | SourceRange InstantiationRange = SourceRange()); | |||
7605 | ||||
7606 | /// Note that we are substituting prior template arguments into a | |||
7607 | /// non-type parameter. | |||
7608 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7609 | NamedDecl *Template, | |||
7610 | NonTypeTemplateParmDecl *Param, | |||
7611 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7612 | SourceRange InstantiationRange); | |||
7613 | ||||
7614 | /// Note that we are substituting prior template arguments into a | |||
7615 | /// template template parameter. | |||
7616 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7617 | NamedDecl *Template, | |||
7618 | TemplateTemplateParmDecl *Param, | |||
7619 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7620 | SourceRange InstantiationRange); | |||
7621 | ||||
7622 | /// Note that we are checking the default template argument | |||
7623 | /// against the template parameter for a given template-id. | |||
7624 | InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, | |||
7625 | TemplateDecl *Template, | |||
7626 | NamedDecl *Param, | |||
7627 | ArrayRef<TemplateArgument> TemplateArgs, | |||
7628 | SourceRange InstantiationRange); | |||
7629 | ||||
7630 | ||||
7631 | /// Note that we have finished instantiating this template. | |||
7632 | void Clear(); | |||
7633 | ||||
7634 | ~InstantiatingTemplate() { Clear(); } | |||
7635 | ||||
7636 | /// Determines whether we have exceeded the maximum | |||
7637 | /// recursive template instantiations. | |||
7638 | bool isInvalid() const { return Invalid; } | |||
7639 | ||||
7640 | /// Determine whether we are already instantiating this | |||
7641 | /// specialization in some surrounding active instantiation. | |||
7642 | bool isAlreadyInstantiating() const { return AlreadyInstantiating; } | |||
7643 | ||||
7644 | private: | |||
7645 | Sema &SemaRef; | |||
7646 | bool Invalid; | |||
7647 | bool AlreadyInstantiating; | |||
7648 | bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, | |||
7649 | SourceRange InstantiationRange); | |||
7650 | ||||
7651 | InstantiatingTemplate( | |||
7652 | Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, | |||
7653 | SourceLocation PointOfInstantiation, SourceRange InstantiationRange, | |||
7654 | Decl *Entity, NamedDecl *Template = nullptr, | |||
7655 | ArrayRef<TemplateArgument> TemplateArgs = None, | |||
7656 | sema::TemplateDeductionInfo *DeductionInfo = nullptr); | |||
7657 | ||||
7658 | InstantiatingTemplate(const InstantiatingTemplate&) = delete; | |||
7659 | ||||
7660 | InstantiatingTemplate& | |||
7661 | operator=(const InstantiatingTemplate&) = delete; | |||
7662 | }; | |||
7663 | ||||
7664 | void pushCodeSynthesisContext(CodeSynthesisContext Ctx); | |||
7665 | void popCodeSynthesisContext(); | |||
7666 | ||||
7667 | /// Determine whether we are currently performing template instantiation. | |||
7668 | bool inTemplateInstantiation() const { | |||
7669 | return CodeSynthesisContexts.size() > NonInstantiationEntries; | |||
7670 | } | |||
7671 | ||||
7672 | void PrintContextStack() { | |||
7673 | if (!CodeSynthesisContexts.empty() && | |||
7674 | CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { | |||
7675 | PrintInstantiationStack(); | |||
7676 | LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); | |||
7677 | } | |||
7678 | if (PragmaAttributeCurrentTargetDecl) | |||
7679 | PrintPragmaAttributeInstantiationPoint(); | |||
7680 | } | |||
7681 | void PrintInstantiationStack(); | |||
7682 | ||||
7683 | void PrintPragmaAttributeInstantiationPoint(); | |||
7684 | ||||
7685 | /// Determines whether we are currently in a context where | |||
7686 | /// template argument substitution failures are not considered | |||
7687 | /// errors. | |||
7688 | /// | |||
7689 | /// \returns An empty \c Optional if we're not in a SFINAE context. | |||
7690 | /// Otherwise, contains a pointer that, if non-NULL, contains the nearest | |||
7691 | /// template-deduction context object, which can be used to capture | |||
7692 | /// diagnostics that will be suppressed. | |||
7693 | Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; | |||
7694 | ||||
7695 | /// Determines whether we are currently in a context that | |||
7696 | /// is not evaluated as per C++ [expr] p5. | |||
7697 | bool isUnevaluatedContext() const { | |||
7698 | assert(!ExprEvalContexts.empty() &&((!ExprEvalContexts.empty() && "Must be in an expression evaluation context" ) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7699, __PRETTY_FUNCTION__)) | |||
7699 | "Must be in an expression evaluation context")((!ExprEvalContexts.empty() && "Must be in an expression evaluation context" ) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7699, __PRETTY_FUNCTION__)); | |||
7700 | return ExprEvalContexts.back().isUnevaluated(); | |||
7701 | } | |||
7702 | ||||
7703 | /// RAII class used to determine whether SFINAE has | |||
7704 | /// trapped any errors that occur during template argument | |||
7705 | /// deduction. | |||
7706 | class SFINAETrap { | |||
7707 | Sema &SemaRef; | |||
7708 | unsigned PrevSFINAEErrors; | |||
7709 | bool PrevInNonInstantiationSFINAEContext; | |||
7710 | bool PrevAccessCheckingSFINAE; | |||
7711 | bool PrevLastDiagnosticIgnored; | |||
7712 | ||||
7713 | public: | |||
7714 | explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) | |||
7715 | : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), | |||
7716 | PrevInNonInstantiationSFINAEContext( | |||
7717 | SemaRef.InNonInstantiationSFINAEContext), | |||
7718 | PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), | |||
7719 | PrevLastDiagnosticIgnored( | |||
7720 | SemaRef.getDiagnostics().isLastDiagnosticIgnored()) | |||
7721 | { | |||
7722 | if (!SemaRef.isSFINAEContext()) | |||
7723 | SemaRef.InNonInstantiationSFINAEContext = true; | |||
7724 | SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; | |||
7725 | } | |||
7726 | ||||
7727 | ~SFINAETrap() { | |||
7728 | SemaRef.NumSFINAEErrors = PrevSFINAEErrors; | |||
7729 | SemaRef.InNonInstantiationSFINAEContext | |||
7730 | = PrevInNonInstantiationSFINAEContext; | |||
7731 | SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; | |||
7732 | SemaRef.getDiagnostics().setLastDiagnosticIgnored( | |||
7733 | PrevLastDiagnosticIgnored); | |||
7734 | } | |||
7735 | ||||
7736 | /// Determine whether any SFINAE errors have been trapped. | |||
7737 | bool hasErrorOccurred() const { | |||
7738 | return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; | |||
7739 | } | |||
7740 | }; | |||
7741 | ||||
7742 | /// RAII class used to indicate that we are performing provisional | |||
7743 | /// semantic analysis to determine the validity of a construct, so | |||
7744 | /// typo-correction and diagnostics in the immediate context (not within | |||
7745 | /// implicitly-instantiated templates) should be suppressed. | |||
7746 | class TentativeAnalysisScope { | |||
7747 | Sema &SemaRef; | |||
7748 | // FIXME: Using a SFINAETrap for this is a hack. | |||
7749 | SFINAETrap Trap; | |||
7750 | bool PrevDisableTypoCorrection; | |||
7751 | public: | |||
7752 | explicit TentativeAnalysisScope(Sema &SemaRef) | |||
7753 | : SemaRef(SemaRef), Trap(SemaRef, true), | |||
7754 | PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { | |||
7755 | SemaRef.DisableTypoCorrection = true; | |||
7756 | } | |||
7757 | ~TentativeAnalysisScope() { | |||
7758 | SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; | |||
7759 | } | |||
7760 | }; | |||
7761 | ||||
7762 | /// The current instantiation scope used to store local | |||
7763 | /// variables. | |||
7764 | LocalInstantiationScope *CurrentInstantiationScope; | |||
7765 | ||||
7766 | /// Tracks whether we are in a context where typo correction is | |||
7767 | /// disabled. | |||
7768 | bool DisableTypoCorrection; | |||
7769 | ||||
7770 | /// The number of typos corrected by CorrectTypo. | |||
7771 | unsigned TyposCorrected; | |||
7772 | ||||
7773 | typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; | |||
7774 | typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; | |||
7775 | ||||
7776 | /// A cache containing identifiers for which typo correction failed and | |||
7777 | /// their locations, so that repeated attempts to correct an identifier in a | |||
7778 | /// given location are ignored if typo correction already failed for it. | |||
7779 | IdentifierSourceLocations TypoCorrectionFailures; | |||
7780 | ||||
7781 | /// Worker object for performing CFG-based warnings. | |||
7782 | sema::AnalysisBasedWarnings AnalysisWarnings; | |||
7783 | threadSafety::BeforeSet *ThreadSafetyDeclCache; | |||
7784 | ||||
7785 | /// An entity for which implicit template instantiation is required. | |||
7786 | /// | |||
7787 | /// The source location associated with the declaration is the first place in | |||
7788 | /// the source code where the declaration was "used". It is not necessarily | |||
7789 | /// the point of instantiation (which will be either before or after the | |||
7790 | /// namespace-scope declaration that triggered this implicit instantiation), | |||
7791 | /// However, it is the location that diagnostics should generally refer to, | |||
7792 | /// because users will need to know what code triggered the instantiation. | |||
7793 | typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; | |||
7794 | ||||
7795 | /// The queue of implicit template instantiations that are required | |||
7796 | /// but have not yet been performed. | |||
7797 | std::deque<PendingImplicitInstantiation> PendingInstantiations; | |||
7798 | ||||
7799 | /// Queue of implicit template instantiations that cannot be performed | |||
7800 | /// eagerly. | |||
7801 | SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; | |||
7802 | ||||
7803 | class GlobalEagerInstantiationScope { | |||
7804 | public: | |||
7805 | GlobalEagerInstantiationScope(Sema &S, bool Enabled) | |||
7806 | : S(S), Enabled(Enabled) { | |||
7807 | if (!Enabled) return; | |||
7808 | ||||
7809 | SavedPendingInstantiations.swap(S.PendingInstantiations); | |||
7810 | SavedVTableUses.swap(S.VTableUses); | |||
7811 | } | |||
7812 | ||||
7813 | void perform() { | |||
7814 | if (Enabled) { | |||
7815 | S.DefineUsedVTables(); | |||
7816 | S.PerformPendingInstantiations(); | |||
7817 | } | |||
7818 | } | |||
7819 | ||||
7820 | ~GlobalEagerInstantiationScope() { | |||
7821 | if (!Enabled) return; | |||
7822 | ||||
7823 | // Restore the set of pending vtables. | |||
7824 | assert(S.VTableUses.empty() &&((S.VTableUses.empty() && "VTableUses should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7825, __PRETTY_FUNCTION__)) | |||
7825 | "VTableUses should be empty before it is discarded.")((S.VTableUses.empty() && "VTableUses should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7825, __PRETTY_FUNCTION__)); | |||
7826 | S.VTableUses.swap(SavedVTableUses); | |||
7827 | ||||
7828 | // Restore the set of pending implicit instantiations. | |||
7829 | assert(S.PendingInstantiations.empty() &&((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7830, __PRETTY_FUNCTION__)) | |||
7830 | "PendingInstantiations should be empty before it is discarded.")((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded." ) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7830, __PRETTY_FUNCTION__)); | |||
7831 | S.PendingInstantiations.swap(SavedPendingInstantiations); | |||
7832 | } | |||
7833 | ||||
7834 | private: | |||
7835 | Sema &S; | |||
7836 | SmallVector<VTableUse, 16> SavedVTableUses; | |||
7837 | std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; | |||
7838 | bool Enabled; | |||
7839 | }; | |||
7840 | ||||
7841 | /// The queue of implicit template instantiations that are required | |||
7842 | /// and must be performed within the current local scope. | |||
7843 | /// | |||
7844 | /// This queue is only used for member functions of local classes in | |||
7845 | /// templates, which must be instantiated in the same scope as their | |||
7846 | /// enclosing function, so that they can reference function-local | |||
7847 | /// types, static variables, enumerators, etc. | |||
7848 | std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; | |||
7849 | ||||
7850 | class LocalEagerInstantiationScope { | |||
7851 | public: | |||
7852 | LocalEagerInstantiationScope(Sema &S) : S(S) { | |||
7853 | SavedPendingLocalImplicitInstantiations.swap( | |||
7854 | S.PendingLocalImplicitInstantiations); | |||
7855 | } | |||
7856 | ||||
7857 | void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } | |||
7858 | ||||
7859 | ~LocalEagerInstantiationScope() { | |||
7860 | assert(S.PendingLocalImplicitInstantiations.empty() &&((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations" ) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7861, __PRETTY_FUNCTION__)) | |||
7861 | "there shouldn't be any pending local implicit instantiations")((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations" ) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7861, __PRETTY_FUNCTION__)); | |||
7862 | SavedPendingLocalImplicitInstantiations.swap( | |||
7863 | S.PendingLocalImplicitInstantiations); | |||
7864 | } | |||
7865 | ||||
7866 | private: | |||
7867 | Sema &S; | |||
7868 | std::deque<PendingImplicitInstantiation> | |||
7869 | SavedPendingLocalImplicitInstantiations; | |||
7870 | }; | |||
7871 | ||||
7872 | /// A helper class for building up ExtParameterInfos. | |||
7873 | class ExtParameterInfoBuilder { | |||
7874 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; | |||
7875 | bool HasInteresting = false; | |||
7876 | ||||
7877 | public: | |||
7878 | /// Set the ExtParameterInfo for the parameter at the given index, | |||
7879 | /// | |||
7880 | void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { | |||
7881 | assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail ("Infos.size() <= index", "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 7881, __PRETTY_FUNCTION__)); | |||
7882 | Infos.resize(index); | |||
7883 | Infos.push_back(info); | |||
7884 | ||||
7885 | if (!HasInteresting) | |||
7886 | HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); | |||
7887 | } | |||
7888 | ||||
7889 | /// Return a pointer (suitable for setting in an ExtProtoInfo) to the | |||
7890 | /// ExtParameterInfo array we've built up. | |||
7891 | const FunctionProtoType::ExtParameterInfo * | |||
7892 | getPointerOrNull(unsigned numParams) { | |||
7893 | if (!HasInteresting) return nullptr; | |||
7894 | Infos.resize(numParams); | |||
7895 | return Infos.data(); | |||
7896 | } | |||
7897 | }; | |||
7898 | ||||
7899 | void PerformPendingInstantiations(bool LocalOnly = false); | |||
7900 | ||||
7901 | TypeSourceInfo *SubstType(TypeSourceInfo *T, | |||
7902 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7903 | SourceLocation Loc, DeclarationName Entity, | |||
7904 | bool AllowDeducedTST = false); | |||
7905 | ||||
7906 | QualType SubstType(QualType T, | |||
7907 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7908 | SourceLocation Loc, DeclarationName Entity); | |||
7909 | ||||
7910 | TypeSourceInfo *SubstType(TypeLoc TL, | |||
7911 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7912 | SourceLocation Loc, DeclarationName Entity); | |||
7913 | ||||
7914 | TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, | |||
7915 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7916 | SourceLocation Loc, | |||
7917 | DeclarationName Entity, | |||
7918 | CXXRecordDecl *ThisContext, | |||
7919 | Qualifiers ThisTypeQuals); | |||
7920 | void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, | |||
7921 | const MultiLevelTemplateArgumentList &Args); | |||
7922 | bool SubstExceptionSpec(SourceLocation Loc, | |||
7923 | FunctionProtoType::ExceptionSpecInfo &ESI, | |||
7924 | SmallVectorImpl<QualType> &ExceptionStorage, | |||
7925 | const MultiLevelTemplateArgumentList &Args); | |||
7926 | ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, | |||
7927 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7928 | int indexAdjustment, | |||
7929 | Optional<unsigned> NumExpansions, | |||
7930 | bool ExpectParameterPack); | |||
7931 | bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, | |||
7932 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, | |||
7933 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7934 | SmallVectorImpl<QualType> &ParamTypes, | |||
7935 | SmallVectorImpl<ParmVarDecl *> *OutParams, | |||
7936 | ExtParameterInfoBuilder &ParamInfos); | |||
7937 | ExprResult SubstExpr(Expr *E, | |||
7938 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
7939 | ||||
7940 | /// Substitute the given template arguments into a list of | |||
7941 | /// expressions, expanding pack expansions if required. | |||
7942 | /// | |||
7943 | /// \param Exprs The list of expressions to substitute into. | |||
7944 | /// | |||
7945 | /// \param IsCall Whether this is some form of call, in which case | |||
7946 | /// default arguments will be dropped. | |||
7947 | /// | |||
7948 | /// \param TemplateArgs The set of template arguments to substitute. | |||
7949 | /// | |||
7950 | /// \param Outputs Will receive all of the substituted arguments. | |||
7951 | /// | |||
7952 | /// \returns true if an error occurred, false otherwise. | |||
7953 | bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, | |||
7954 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7955 | SmallVectorImpl<Expr *> &Outputs); | |||
7956 | ||||
7957 | StmtResult SubstStmt(Stmt *S, | |||
7958 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
7959 | ||||
7960 | TemplateParameterList * | |||
7961 | SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, | |||
7962 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
7963 | ||||
7964 | Decl *SubstDecl(Decl *D, DeclContext *Owner, | |||
7965 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
7966 | ||||
7967 | ExprResult SubstInitializer(Expr *E, | |||
7968 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7969 | bool CXXDirectInit); | |||
7970 | ||||
7971 | bool | |||
7972 | SubstBaseSpecifiers(CXXRecordDecl *Instantiation, | |||
7973 | CXXRecordDecl *Pattern, | |||
7974 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
7975 | ||||
7976 | bool | |||
7977 | InstantiateClass(SourceLocation PointOfInstantiation, | |||
7978 | CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, | |||
7979 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7980 | TemplateSpecializationKind TSK, | |||
7981 | bool Complain = true); | |||
7982 | ||||
7983 | bool InstantiateEnum(SourceLocation PointOfInstantiation, | |||
7984 | EnumDecl *Instantiation, EnumDecl *Pattern, | |||
7985 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
7986 | TemplateSpecializationKind TSK); | |||
7987 | ||||
7988 | bool InstantiateInClassInitializer( | |||
7989 | SourceLocation PointOfInstantiation, FieldDecl *Instantiation, | |||
7990 | FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); | |||
7991 | ||||
7992 | struct LateInstantiatedAttribute { | |||
7993 | const Attr *TmplAttr; | |||
7994 | LocalInstantiationScope *Scope; | |||
7995 | Decl *NewDecl; | |||
7996 | ||||
7997 | LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, | |||
7998 | Decl *D) | |||
7999 | : TmplAttr(A), Scope(S), NewDecl(D) | |||
8000 | { } | |||
8001 | }; | |||
8002 | typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; | |||
8003 | ||||
8004 | void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, | |||
8005 | const Decl *Pattern, Decl *Inst, | |||
8006 | LateInstantiatedAttrVec *LateAttrs = nullptr, | |||
8007 | LocalInstantiationScope *OuterMostScope = nullptr); | |||
8008 | ||||
8009 | void | |||
8010 | InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, | |||
8011 | const Decl *Pattern, Decl *Inst, | |||
8012 | LateInstantiatedAttrVec *LateAttrs = nullptr, | |||
8013 | LocalInstantiationScope *OuterMostScope = nullptr); | |||
8014 | ||||
8015 | bool usesPartialOrExplicitSpecialization( | |||
8016 | SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); | |||
8017 | ||||
8018 | bool | |||
8019 | InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, | |||
8020 | ClassTemplateSpecializationDecl *ClassTemplateSpec, | |||
8021 | TemplateSpecializationKind TSK, | |||
8022 | bool Complain = true); | |||
8023 | ||||
8024 | void InstantiateClassMembers(SourceLocation PointOfInstantiation, | |||
8025 | CXXRecordDecl *Instantiation, | |||
8026 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
8027 | TemplateSpecializationKind TSK); | |||
8028 | ||||
8029 | void InstantiateClassTemplateSpecializationMembers( | |||
8030 | SourceLocation PointOfInstantiation, | |||
8031 | ClassTemplateSpecializationDecl *ClassTemplateSpec, | |||
8032 | TemplateSpecializationKind TSK); | |||
8033 | ||||
8034 | NestedNameSpecifierLoc | |||
8035 | SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, | |||
8036 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8037 | ||||
8038 | DeclarationNameInfo | |||
8039 | SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, | |||
8040 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8041 | TemplateName | |||
8042 | SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, | |||
8043 | SourceLocation Loc, | |||
8044 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8045 | bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, | |||
8046 | TemplateArgumentListInfo &Result, | |||
8047 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8048 | ||||
8049 | void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, | |||
8050 | FunctionDecl *Function); | |||
8051 | FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, | |||
8052 | const TemplateArgumentList *Args, | |||
8053 | SourceLocation Loc); | |||
8054 | void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, | |||
8055 | FunctionDecl *Function, | |||
8056 | bool Recursive = false, | |||
8057 | bool DefinitionRequired = false, | |||
8058 | bool AtEndOfTU = false); | |||
8059 | VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( | |||
8060 | VarTemplateDecl *VarTemplate, VarDecl *FromVar, | |||
8061 | const TemplateArgumentList &TemplateArgList, | |||
8062 | const TemplateArgumentListInfo &TemplateArgsInfo, | |||
8063 | SmallVectorImpl<TemplateArgument> &Converted, | |||
8064 | SourceLocation PointOfInstantiation, void *InsertPos, | |||
8065 | LateInstantiatedAttrVec *LateAttrs = nullptr, | |||
8066 | LocalInstantiationScope *StartingScope = nullptr); | |||
8067 | VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( | |||
8068 | VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, | |||
8069 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8070 | void | |||
8071 | BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, | |||
8072 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
8073 | LateInstantiatedAttrVec *LateAttrs, | |||
8074 | DeclContext *Owner, | |||
8075 | LocalInstantiationScope *StartingScope, | |||
8076 | bool InstantiatingVarTemplate = false, | |||
8077 | VarTemplateSpecializationDecl *PrevVTSD = nullptr); | |||
8078 | void InstantiateVariableInitializer( | |||
8079 | VarDecl *Var, VarDecl *OldVar, | |||
8080 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8081 | void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, | |||
8082 | VarDecl *Var, bool Recursive = false, | |||
8083 | bool DefinitionRequired = false, | |||
8084 | bool AtEndOfTU = false); | |||
8085 | ||||
8086 | void InstantiateMemInitializers(CXXConstructorDecl *New, | |||
8087 | const CXXConstructorDecl *Tmpl, | |||
8088 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8089 | ||||
8090 | NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, | |||
8091 | const MultiLevelTemplateArgumentList &TemplateArgs, | |||
8092 | bool FindingInstantiatedContext = false); | |||
8093 | DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, | |||
8094 | const MultiLevelTemplateArgumentList &TemplateArgs); | |||
8095 | ||||
8096 | // Objective-C declarations. | |||
8097 | enum ObjCContainerKind { | |||
8098 | OCK_None = -1, | |||
8099 | OCK_Interface = 0, | |||
8100 | OCK_Protocol, | |||
8101 | OCK_Category, | |||
8102 | OCK_ClassExtension, | |||
8103 | OCK_Implementation, | |||
8104 | OCK_CategoryImplementation | |||
8105 | }; | |||
8106 | ObjCContainerKind getObjCContainerKind() const; | |||
8107 | ||||
8108 | DeclResult actOnObjCTypeParam(Scope *S, | |||
8109 | ObjCTypeParamVariance variance, | |||
8110 | SourceLocation varianceLoc, | |||
8111 | unsigned index, | |||
8112 | IdentifierInfo *paramName, | |||
8113 | SourceLocation paramLoc, | |||
8114 | SourceLocation colonLoc, | |||
8115 | ParsedType typeBound); | |||
8116 | ||||
8117 | ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, | |||
8118 | ArrayRef<Decl *> typeParams, | |||
8119 | SourceLocation rAngleLoc); | |||
8120 | void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); | |||
8121 | ||||
8122 | Decl *ActOnStartClassInterface( | |||
8123 | Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, | |||
8124 | SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, | |||
8125 | IdentifierInfo *SuperName, SourceLocation SuperLoc, | |||
8126 | ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, | |||
8127 | Decl *const *ProtoRefs, unsigned NumProtoRefs, | |||
8128 | const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, | |||
8129 | const ParsedAttributesView &AttrList); | |||
8130 | ||||
8131 | void ActOnSuperClassOfClassInterface(Scope *S, | |||
8132 | SourceLocation AtInterfaceLoc, | |||
8133 | ObjCInterfaceDecl *IDecl, | |||
8134 | IdentifierInfo *ClassName, | |||
8135 | SourceLocation ClassLoc, | |||
8136 | IdentifierInfo *SuperName, | |||
8137 | SourceLocation SuperLoc, | |||
8138 | ArrayRef<ParsedType> SuperTypeArgs, | |||
8139 | SourceRange SuperTypeArgsRange); | |||
8140 | ||||
8141 | void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, | |||
8142 | SmallVectorImpl<SourceLocation> &ProtocolLocs, | |||
8143 | IdentifierInfo *SuperName, | |||
8144 | SourceLocation SuperLoc); | |||
8145 | ||||
8146 | Decl *ActOnCompatibilityAlias( | |||
8147 | SourceLocation AtCompatibilityAliasLoc, | |||
8148 | IdentifierInfo *AliasName, SourceLocation AliasLocation, | |||
8149 | IdentifierInfo *ClassName, SourceLocation ClassLocation); | |||
8150 | ||||
8151 | bool CheckForwardProtocolDeclarationForCircularDependency( | |||
8152 | IdentifierInfo *PName, | |||
8153 | SourceLocation &PLoc, SourceLocation PrevLoc, | |||
8154 | const ObjCList<ObjCProtocolDecl> &PList); | |||
8155 | ||||
8156 | Decl *ActOnStartProtocolInterface( | |||
8157 | SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, | |||
8158 | SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, | |||
8159 | unsigned NumProtoRefs, const SourceLocation *ProtoLocs, | |||
8160 | SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); | |||
8161 | ||||
8162 | Decl *ActOnStartCategoryInterface( | |||
8163 | SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, | |||
8164 | SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, | |||
8165 | IdentifierInfo *CategoryName, SourceLocation CategoryLoc, | |||
8166 | Decl *const *ProtoRefs, unsigned NumProtoRefs, | |||
8167 | const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, | |||
8168 | const ParsedAttributesView &AttrList); | |||
8169 | ||||
8170 | Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, | |||
8171 | IdentifierInfo *ClassName, | |||
8172 | SourceLocation ClassLoc, | |||
8173 | IdentifierInfo *SuperClassname, | |||
8174 | SourceLocation SuperClassLoc, | |||
8175 | const ParsedAttributesView &AttrList); | |||
8176 | ||||
8177 | Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, | |||
8178 | IdentifierInfo *ClassName, | |||
8179 | SourceLocation ClassLoc, | |||
8180 | IdentifierInfo *CatName, | |||
8181 | SourceLocation CatLoc, | |||
8182 | const ParsedAttributesView &AttrList); | |||
8183 | ||||
8184 | DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, | |||
8185 | ArrayRef<Decl *> Decls); | |||
8186 | ||||
8187 | DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, | |||
8188 | IdentifierInfo **IdentList, | |||
8189 | SourceLocation *IdentLocs, | |||
8190 | ArrayRef<ObjCTypeParamList *> TypeParamLists, | |||
8191 | unsigned NumElts); | |||
8192 | ||||
8193 | DeclGroupPtrTy | |||
8194 | ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, | |||
8195 | ArrayRef<IdentifierLocPair> IdentList, | |||
8196 | const ParsedAttributesView &attrList); | |||
8197 | ||||
8198 | void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, | |||
8199 | ArrayRef<IdentifierLocPair> ProtocolId, | |||
8200 | SmallVectorImpl<Decl *> &Protocols); | |||
8201 | ||||
8202 | void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, | |||
8203 | SourceLocation ProtocolLoc, | |||
8204 | IdentifierInfo *TypeArgId, | |||
8205 | SourceLocation TypeArgLoc, | |||
8206 | bool SelectProtocolFirst = false); | |||
8207 | ||||
8208 | /// Given a list of identifiers (and their locations), resolve the | |||
8209 | /// names to either Objective-C protocol qualifiers or type | |||
8210 | /// arguments, as appropriate. | |||
8211 | void actOnObjCTypeArgsOrProtocolQualifiers( | |||
8212 | Scope *S, | |||
8213 | ParsedType baseType, | |||
8214 | SourceLocation lAngleLoc, | |||
8215 | ArrayRef<IdentifierInfo *> identifiers, | |||
8216 | ArrayRef<SourceLocation> identifierLocs, | |||
8217 | SourceLocation rAngleLoc, | |||
8218 | SourceLocation &typeArgsLAngleLoc, | |||
8219 | SmallVectorImpl<ParsedType> &typeArgs, | |||
8220 | SourceLocation &typeArgsRAngleLoc, | |||
8221 | SourceLocation &protocolLAngleLoc, | |||
8222 | SmallVectorImpl<Decl *> &protocols, | |||
8223 | SourceLocation &protocolRAngleLoc, | |||
8224 | bool warnOnIncompleteProtocols); | |||
8225 | ||||
8226 | /// Build a an Objective-C protocol-qualified 'id' type where no | |||
8227 | /// base type was specified. | |||
8228 | TypeResult actOnObjCProtocolQualifierType( | |||
8229 | SourceLocation lAngleLoc, | |||
8230 | ArrayRef<Decl *> protocols, | |||
8231 | ArrayRef<SourceLocation> protocolLocs, | |||
8232 | SourceLocation rAngleLoc); | |||
8233 | ||||
8234 | /// Build a specialized and/or protocol-qualified Objective-C type. | |||
8235 | TypeResult actOnObjCTypeArgsAndProtocolQualifiers( | |||
8236 | Scope *S, | |||
8237 | SourceLocation Loc, | |||
8238 | ParsedType BaseType, | |||
8239 | SourceLocation TypeArgsLAngleLoc, | |||
8240 | ArrayRef<ParsedType> TypeArgs, | |||
8241 | SourceLocation TypeArgsRAngleLoc, | |||
8242 | SourceLocation ProtocolLAngleLoc, | |||
8243 | ArrayRef<Decl *> Protocols, | |||
8244 | ArrayRef<SourceLocation> ProtocolLocs, | |||
8245 | SourceLocation ProtocolRAngleLoc); | |||
8246 | ||||
8247 | /// Build an Objective-C type parameter type. | |||
8248 | QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, | |||
8249 | SourceLocation ProtocolLAngleLoc, | |||
8250 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
8251 | ArrayRef<SourceLocation> ProtocolLocs, | |||
8252 | SourceLocation ProtocolRAngleLoc, | |||
8253 | bool FailOnError = false); | |||
8254 | ||||
8255 | /// Build an Objective-C object pointer type. | |||
8256 | QualType BuildObjCObjectType(QualType BaseType, | |||
8257 | SourceLocation Loc, | |||
8258 | SourceLocation TypeArgsLAngleLoc, | |||
8259 | ArrayRef<TypeSourceInfo *> TypeArgs, | |||
8260 | SourceLocation TypeArgsRAngleLoc, | |||
8261 | SourceLocation ProtocolLAngleLoc, | |||
8262 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
8263 | ArrayRef<SourceLocation> ProtocolLocs, | |||
8264 | SourceLocation ProtocolRAngleLoc, | |||
8265 | bool FailOnError = false); | |||
8266 | ||||
8267 | /// Ensure attributes are consistent with type. | |||
8268 | /// \param [in, out] Attributes The attributes to check; they will | |||
8269 | /// be modified to be consistent with \p PropertyTy. | |||
8270 | void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, | |||
8271 | SourceLocation Loc, | |||
8272 | unsigned &Attributes, | |||
8273 | bool propertyInPrimaryClass); | |||
8274 | ||||
8275 | /// Process the specified property declaration and create decls for the | |||
8276 | /// setters and getters as needed. | |||
8277 | /// \param property The property declaration being processed | |||
8278 | void ProcessPropertyDecl(ObjCPropertyDecl *property); | |||
8279 | ||||
8280 | ||||
8281 | void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, | |||
8282 | ObjCPropertyDecl *SuperProperty, | |||
8283 | const IdentifierInfo *Name, | |||
8284 | bool OverridingProtocolProperty); | |||
8285 | ||||
8286 | void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, | |||
8287 | ObjCInterfaceDecl *ID); | |||
8288 | ||||
8289 | Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, | |||
8290 | ArrayRef<Decl *> allMethods = None, | |||
8291 | ArrayRef<DeclGroupPtrTy> allTUVars = None); | |||
8292 | ||||
8293 | Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, | |||
8294 | SourceLocation LParenLoc, | |||
8295 | FieldDeclarator &FD, ObjCDeclSpec &ODS, | |||
8296 | Selector GetterSel, Selector SetterSel, | |||
8297 | tok::ObjCKeywordKind MethodImplKind, | |||
8298 | DeclContext *lexicalDC = nullptr); | |||
8299 | ||||
8300 | Decl *ActOnPropertyImplDecl(Scope *S, | |||
8301 | SourceLocation AtLoc, | |||
8302 | SourceLocation PropertyLoc, | |||
8303 | bool ImplKind, | |||
8304 | IdentifierInfo *PropertyId, | |||
8305 | IdentifierInfo *PropertyIvar, | |||
8306 | SourceLocation PropertyIvarLoc, | |||
8307 | ObjCPropertyQueryKind QueryKind); | |||
8308 | ||||
8309 | enum ObjCSpecialMethodKind { | |||
8310 | OSMK_None, | |||
8311 | OSMK_Alloc, | |||
8312 | OSMK_New, | |||
8313 | OSMK_Copy, | |||
8314 | OSMK_RetainingInit, | |||
8315 | OSMK_NonRetainingInit | |||
8316 | }; | |||
8317 | ||||
8318 | struct ObjCArgInfo { | |||
8319 | IdentifierInfo *Name; | |||
8320 | SourceLocation NameLoc; | |||
8321 | // The Type is null if no type was specified, and the DeclSpec is invalid | |||
8322 | // in this case. | |||
8323 | ParsedType Type; | |||
8324 | ObjCDeclSpec DeclSpec; | |||
8325 | ||||
8326 | /// ArgAttrs - Attribute list for this argument. | |||
8327 | ParsedAttributesView ArgAttrs; | |||
8328 | }; | |||
8329 | ||||
8330 | Decl *ActOnMethodDeclaration( | |||
8331 | Scope *S, | |||
8332 | SourceLocation BeginLoc, // location of the + or -. | |||
8333 | SourceLocation EndLoc, // location of the ; or {. | |||
8334 | tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, | |||
8335 | ArrayRef<SourceLocation> SelectorLocs, Selector Sel, | |||
8336 | // optional arguments. The number of types/arguments is obtained | |||
8337 | // from the Sel.getNumArgs(). | |||
8338 | ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, | |||
8339 | unsigned CNumArgs, // c-style args | |||
8340 | const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, | |||
8341 | bool isVariadic, bool MethodDefinition); | |||
8342 | ||||
8343 | ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, | |||
8344 | const ObjCObjectPointerType *OPT, | |||
8345 | bool IsInstance); | |||
8346 | ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, | |||
8347 | bool IsInstance); | |||
8348 | ||||
8349 | bool CheckARCMethodDecl(ObjCMethodDecl *method); | |||
8350 | bool inferObjCARCLifetime(ValueDecl *decl); | |||
8351 | ||||
8352 | ExprResult | |||
8353 | HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, | |||
8354 | Expr *BaseExpr, | |||
8355 | SourceLocation OpLoc, | |||
8356 | DeclarationName MemberName, | |||
8357 | SourceLocation MemberLoc, | |||
8358 | SourceLocation SuperLoc, QualType SuperType, | |||
8359 | bool Super); | |||
8360 | ||||
8361 | ExprResult | |||
8362 | ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, | |||
8363 | IdentifierInfo &propertyName, | |||
8364 | SourceLocation receiverNameLoc, | |||
8365 | SourceLocation propertyNameLoc); | |||
8366 | ||||
8367 | ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); | |||
8368 | ||||
8369 | /// Describes the kind of message expression indicated by a message | |||
8370 | /// send that starts with an identifier. | |||
8371 | enum ObjCMessageKind { | |||
8372 | /// The message is sent to 'super'. | |||
8373 | ObjCSuperMessage, | |||
8374 | /// The message is an instance message. | |||
8375 | ObjCInstanceMessage, | |||
8376 | /// The message is a class message, and the identifier is a type | |||
8377 | /// name. | |||
8378 | ObjCClassMessage | |||
8379 | }; | |||
8380 | ||||
8381 | ObjCMessageKind getObjCMessageKind(Scope *S, | |||
8382 | IdentifierInfo *Name, | |||
8383 | SourceLocation NameLoc, | |||
8384 | bool IsSuper, | |||
8385 | bool HasTrailingDot, | |||
8386 | ParsedType &ReceiverType); | |||
8387 | ||||
8388 | ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, | |||
8389 | Selector Sel, | |||
8390 | SourceLocation LBracLoc, | |||
8391 | ArrayRef<SourceLocation> SelectorLocs, | |||
8392 | SourceLocation RBracLoc, | |||
8393 | MultiExprArg Args); | |||
8394 | ||||
8395 | ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, | |||
8396 | QualType ReceiverType, | |||
8397 | SourceLocation SuperLoc, | |||
8398 | Selector Sel, | |||
8399 | ObjCMethodDecl *Method, | |||
8400 | SourceLocation LBracLoc, | |||
8401 | ArrayRef<SourceLocation> SelectorLocs, | |||
8402 | SourceLocation RBracLoc, | |||
8403 | MultiExprArg Args, | |||
8404 | bool isImplicit = false); | |||
8405 | ||||
8406 | ExprResult BuildClassMessageImplicit(QualType ReceiverType, | |||
8407 | bool isSuperReceiver, | |||
8408 | SourceLocation Loc, | |||
8409 | Selector Sel, | |||
8410 | ObjCMethodDecl *Method, | |||
8411 | MultiExprArg Args); | |||
8412 | ||||
8413 | ExprResult ActOnClassMessage(Scope *S, | |||
8414 | ParsedType Receiver, | |||
8415 | Selector Sel, | |||
8416 | SourceLocation LBracLoc, | |||
8417 | ArrayRef<SourceLocation> SelectorLocs, | |||
8418 | SourceLocation RBracLoc, | |||
8419 | MultiExprArg Args); | |||
8420 | ||||
8421 | ExprResult BuildInstanceMessage(Expr *Receiver, | |||
8422 | QualType ReceiverType, | |||
8423 | SourceLocation SuperLoc, | |||
8424 | Selector Sel, | |||
8425 | ObjCMethodDecl *Method, | |||
8426 | SourceLocation LBracLoc, | |||
8427 | ArrayRef<SourceLocation> SelectorLocs, | |||
8428 | SourceLocation RBracLoc, | |||
8429 | MultiExprArg Args, | |||
8430 | bool isImplicit = false); | |||
8431 | ||||
8432 | ExprResult BuildInstanceMessageImplicit(Expr *Receiver, | |||
8433 | QualType ReceiverType, | |||
8434 | SourceLocation Loc, | |||
8435 | Selector Sel, | |||
8436 | ObjCMethodDecl *Method, | |||
8437 | MultiExprArg Args); | |||
8438 | ||||
8439 | ExprResult ActOnInstanceMessage(Scope *S, | |||
8440 | Expr *Receiver, | |||
8441 | Selector Sel, | |||
8442 | SourceLocation LBracLoc, | |||
8443 | ArrayRef<SourceLocation> SelectorLocs, | |||
8444 | SourceLocation RBracLoc, | |||
8445 | MultiExprArg Args); | |||
8446 | ||||
8447 | ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, | |||
8448 | ObjCBridgeCastKind Kind, | |||
8449 | SourceLocation BridgeKeywordLoc, | |||
8450 | TypeSourceInfo *TSInfo, | |||
8451 | Expr *SubExpr); | |||
8452 | ||||
8453 | ExprResult ActOnObjCBridgedCast(Scope *S, | |||
8454 | SourceLocation LParenLoc, | |||
8455 | ObjCBridgeCastKind Kind, | |||
8456 | SourceLocation BridgeKeywordLoc, | |||
8457 | ParsedType Type, | |||
8458 | SourceLocation RParenLoc, | |||
8459 | Expr *SubExpr); | |||
8460 | ||||
8461 | void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); | |||
8462 | ||||
8463 | void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); | |||
8464 | ||||
8465 | bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, | |||
8466 | CastKind &Kind); | |||
8467 | ||||
8468 | bool checkObjCBridgeRelatedComponents(SourceLocation Loc, | |||
8469 | QualType DestType, QualType SrcType, | |||
8470 | ObjCInterfaceDecl *&RelatedClass, | |||
8471 | ObjCMethodDecl *&ClassMethod, | |||
8472 | ObjCMethodDecl *&InstanceMethod, | |||
8473 | TypedefNameDecl *&TDNDecl, | |||
8474 | bool CfToNs, bool Diagnose = true); | |||
8475 | ||||
8476 | bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, | |||
8477 | QualType DestType, QualType SrcType, | |||
8478 | Expr *&SrcExpr, bool Diagnose = true); | |||
8479 | ||||
8480 | bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, | |||
8481 | bool Diagnose = true); | |||
8482 | ||||
8483 | bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); | |||
8484 | ||||
8485 | /// Check whether the given new method is a valid override of the | |||
8486 | /// given overridden method, and set any properties that should be inherited. | |||
8487 | void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, | |||
8488 | const ObjCMethodDecl *Overridden); | |||
8489 | ||||
8490 | /// Describes the compatibility of a result type with its method. | |||
8491 | enum ResultTypeCompatibilityKind { | |||
8492 | RTC_Compatible, | |||
8493 | RTC_Incompatible, | |||
8494 | RTC_Unknown | |||
8495 | }; | |||
8496 | ||||
8497 | void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, | |||
8498 | ObjCInterfaceDecl *CurrentClass, | |||
8499 | ResultTypeCompatibilityKind RTC); | |||
8500 | ||||
8501 | enum PragmaOptionsAlignKind { | |||
8502 | POAK_Native, // #pragma options align=native | |||
8503 | POAK_Natural, // #pragma options align=natural | |||
8504 | POAK_Packed, // #pragma options align=packed | |||
8505 | POAK_Power, // #pragma options align=power | |||
8506 | POAK_Mac68k, // #pragma options align=mac68k | |||
8507 | POAK_Reset // #pragma options align=reset | |||
8508 | }; | |||
8509 | ||||
8510 | /// ActOnPragmaClangSection - Called on well formed \#pragma clang section | |||
8511 | void ActOnPragmaClangSection(SourceLocation PragmaLoc, | |||
8512 | PragmaClangSectionAction Action, | |||
8513 | PragmaClangSectionKind SecKind, StringRef SecName); | |||
8514 | ||||
8515 | /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. | |||
8516 | void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, | |||
8517 | SourceLocation PragmaLoc); | |||
8518 | ||||
8519 | /// ActOnPragmaPack - Called on well formed \#pragma pack(...). | |||
8520 | void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, | |||
8521 | StringRef SlotLabel, Expr *Alignment); | |||
8522 | ||||
8523 | enum class PragmaPackDiagnoseKind { | |||
8524 | NonDefaultStateAtInclude, | |||
8525 | ChangedStateAtExit | |||
8526 | }; | |||
8527 | ||||
8528 | void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, | |||
8529 | SourceLocation IncludeLoc); | |||
8530 | void DiagnoseUnterminatedPragmaPack(); | |||
8531 | ||||
8532 | /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. | |||
8533 | void ActOnPragmaMSStruct(PragmaMSStructKind Kind); | |||
8534 | ||||
8535 | /// ActOnPragmaMSComment - Called on well formed | |||
8536 | /// \#pragma comment(kind, "arg"). | |||
8537 | void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, | |||
8538 | StringRef Arg); | |||
8539 | ||||
8540 | /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma | |||
8541 | /// pointers_to_members(representation method[, general purpose | |||
8542 | /// representation]). | |||
8543 | void ActOnPragmaMSPointersToMembers( | |||
8544 | LangOptions::PragmaMSPointersToMembersKind Kind, | |||
8545 | SourceLocation PragmaLoc); | |||
8546 | ||||
8547 | /// Called on well formed \#pragma vtordisp(). | |||
8548 | void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, | |||
8549 | SourceLocation PragmaLoc, | |||
8550 | MSVtorDispAttr::Mode Value); | |||
8551 | ||||
8552 | enum PragmaSectionKind { | |||
8553 | PSK_DataSeg, | |||
8554 | PSK_BSSSeg, | |||
8555 | PSK_ConstSeg, | |||
8556 | PSK_CodeSeg, | |||
8557 | }; | |||
8558 | ||||
8559 | bool UnifySection(StringRef SectionName, | |||
8560 | int SectionFlags, | |||
8561 | DeclaratorDecl *TheDecl); | |||
8562 | bool UnifySection(StringRef SectionName, | |||
8563 | int SectionFlags, | |||
8564 | SourceLocation PragmaSectionLocation); | |||
8565 | ||||
8566 | /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. | |||
8567 | void ActOnPragmaMSSeg(SourceLocation PragmaLocation, | |||
8568 | PragmaMsStackAction Action, | |||
8569 | llvm::StringRef StackSlotLabel, | |||
8570 | StringLiteral *SegmentName, | |||
8571 | llvm::StringRef PragmaName); | |||
8572 | ||||
8573 | /// Called on well formed \#pragma section(). | |||
8574 | void ActOnPragmaMSSection(SourceLocation PragmaLocation, | |||
8575 | int SectionFlags, StringLiteral *SegmentName); | |||
8576 | ||||
8577 | /// Called on well-formed \#pragma init_seg(). | |||
8578 | void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, | |||
8579 | StringLiteral *SegmentName); | |||
8580 | ||||
8581 | /// Called on #pragma clang __debug dump II | |||
8582 | void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); | |||
8583 | ||||
8584 | /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch | |||
8585 | void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, | |||
8586 | StringRef Value); | |||
8587 | ||||
8588 | /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. | |||
8589 | void ActOnPragmaUnused(const Token &Identifier, | |||
8590 | Scope *curScope, | |||
8591 | SourceLocation PragmaLoc); | |||
8592 | ||||
8593 | /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . | |||
8594 | void ActOnPragmaVisibility(const IdentifierInfo* VisType, | |||
8595 | SourceLocation PragmaLoc); | |||
8596 | ||||
8597 | NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, | |||
8598 | SourceLocation Loc); | |||
8599 | void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); | |||
8600 | ||||
8601 | /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. | |||
8602 | void ActOnPragmaWeakID(IdentifierInfo* WeakName, | |||
8603 | SourceLocation PragmaLoc, | |||
8604 | SourceLocation WeakNameLoc); | |||
8605 | ||||
8606 | /// ActOnPragmaRedefineExtname - Called on well formed | |||
8607 | /// \#pragma redefine_extname oldname newname. | |||
8608 | void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, | |||
8609 | IdentifierInfo* AliasName, | |||
8610 | SourceLocation PragmaLoc, | |||
8611 | SourceLocation WeakNameLoc, | |||
8612 | SourceLocation AliasNameLoc); | |||
8613 | ||||
8614 | /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. | |||
8615 | void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, | |||
8616 | IdentifierInfo* AliasName, | |||
8617 | SourceLocation PragmaLoc, | |||
8618 | SourceLocation WeakNameLoc, | |||
8619 | SourceLocation AliasNameLoc); | |||
8620 | ||||
8621 | /// ActOnPragmaFPContract - Called on well formed | |||
8622 | /// \#pragma {STDC,OPENCL} FP_CONTRACT and | |||
8623 | /// \#pragma clang fp contract | |||
8624 | void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); | |||
8625 | ||||
8626 | /// ActOnPragmaFenvAccess - Called on well formed | |||
8627 | /// \#pragma STDC FENV_ACCESS | |||
8628 | void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); | |||
8629 | ||||
8630 | /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to | |||
8631 | /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. | |||
8632 | void AddAlignmentAttributesForRecord(RecordDecl *RD); | |||
8633 | ||||
8634 | /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. | |||
8635 | void AddMsStructLayoutForRecord(RecordDecl *RD); | |||
8636 | ||||
8637 | /// FreePackedContext - Deallocate and null out PackContext. | |||
8638 | void FreePackedContext(); | |||
8639 | ||||
8640 | /// PushNamespaceVisibilityAttr - Note that we've entered a | |||
8641 | /// namespace with a visibility attribute. | |||
8642 | void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, | |||
8643 | SourceLocation Loc); | |||
8644 | ||||
8645 | /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, | |||
8646 | /// add an appropriate visibility attribute. | |||
8647 | void AddPushedVisibilityAttribute(Decl *RD); | |||
8648 | ||||
8649 | /// PopPragmaVisibility - Pop the top element of the visibility stack; used | |||
8650 | /// for '\#pragma GCC visibility' and visibility attributes on namespaces. | |||
8651 | void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); | |||
8652 | ||||
8653 | /// FreeVisContext - Deallocate and null out VisContext. | |||
8654 | void FreeVisContext(); | |||
8655 | ||||
8656 | /// AddCFAuditedAttribute - Check whether we're currently within | |||
8657 | /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding | |||
8658 | /// the appropriate attribute. | |||
8659 | void AddCFAuditedAttribute(Decl *D); | |||
8660 | ||||
8661 | void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, | |||
8662 | SourceLocation PragmaLoc, | |||
8663 | attr::ParsedSubjectMatchRuleSet Rules); | |||
8664 | void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, | |||
8665 | const IdentifierInfo *Namespace); | |||
8666 | ||||
8667 | /// Called on well-formed '\#pragma clang attribute pop'. | |||
8668 | void ActOnPragmaAttributePop(SourceLocation PragmaLoc, | |||
8669 | const IdentifierInfo *Namespace); | |||
8670 | ||||
8671 | /// Adds the attributes that have been specified using the | |||
8672 | /// '\#pragma clang attribute push' directives to the given declaration. | |||
8673 | void AddPragmaAttributes(Scope *S, Decl *D); | |||
8674 | ||||
8675 | void DiagnoseUnterminatedPragmaAttribute(); | |||
8676 | ||||
8677 | /// Called on well formed \#pragma clang optimize. | |||
8678 | void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); | |||
8679 | ||||
8680 | /// Get the location for the currently active "\#pragma clang optimize | |||
8681 | /// off". If this location is invalid, then the state of the pragma is "on". | |||
8682 | SourceLocation getOptimizeOffPragmaLocation() const { | |||
8683 | return OptimizeOffPragmaLocation; | |||
8684 | } | |||
8685 | ||||
8686 | /// Only called on function definitions; if there is a pragma in scope | |||
8687 | /// with the effect of a range-based optnone, consider marking the function | |||
8688 | /// with attribute optnone. | |||
8689 | void AddRangeBasedOptnone(FunctionDecl *FD); | |||
8690 | ||||
8691 | /// Adds the 'optnone' attribute to the function declaration if there | |||
8692 | /// are no conflicts; Loc represents the location causing the 'optnone' | |||
8693 | /// attribute to be added (usually because of a pragma). | |||
8694 | void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); | |||
8695 | ||||
8696 | /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. | |||
8697 | void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, | |||
8698 | unsigned SpellingListIndex, bool IsPackExpansion); | |||
8699 | void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, | |||
8700 | unsigned SpellingListIndex, bool IsPackExpansion); | |||
8701 | ||||
8702 | /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular | |||
8703 | /// declaration. | |||
8704 | void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, | |||
8705 | unsigned SpellingListIndex); | |||
8706 | ||||
8707 | /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular | |||
8708 | /// declaration. | |||
8709 | void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, | |||
8710 | unsigned SpellingListIndex); | |||
8711 | ||||
8712 | /// AddAlignValueAttr - Adds an align_value attribute to a particular | |||
8713 | /// declaration. | |||
8714 | void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, | |||
8715 | unsigned SpellingListIndex); | |||
8716 | ||||
8717 | /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular | |||
8718 | /// declaration. | |||
8719 | void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, | |||
8720 | Expr *MinBlocks, unsigned SpellingListIndex); | |||
8721 | ||||
8722 | /// AddModeAttr - Adds a mode attribute to a particular declaration. | |||
8723 | void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, | |||
8724 | unsigned SpellingListIndex, bool InInstantiation = false); | |||
8725 | ||||
8726 | void AddParameterABIAttr(SourceRange AttrRange, Decl *D, | |||
8727 | ParameterABI ABI, unsigned SpellingListIndex); | |||
8728 | ||||
8729 | enum class RetainOwnershipKind {NS, CF, OS}; | |||
8730 | void AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex, | |||
8731 | RetainOwnershipKind K, bool IsTemplateInstantiation); | |||
8732 | ||||
8733 | /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size | |||
8734 | /// attribute to a particular declaration. | |||
8735 | void addAMDGPUFlatWorkGroupSizeAttr(SourceRange AttrRange, Decl *D, Expr *Min, | |||
8736 | Expr *Max, unsigned SpellingListIndex); | |||
8737 | ||||
8738 | /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a | |||
8739 | /// particular declaration. | |||
8740 | void addAMDGPUWavesPerEUAttr(SourceRange AttrRange, Decl *D, Expr *Min, | |||
8741 | Expr *Max, unsigned SpellingListIndex); | |||
8742 | ||||
8743 | bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); | |||
8744 | ||||
8745 | //===--------------------------------------------------------------------===// | |||
8746 | // C++ Coroutines TS | |||
8747 | // | |||
8748 | bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, | |||
8749 | StringRef Keyword); | |||
8750 | ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); | |||
8751 | ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); | |||
8752 | StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); | |||
8753 | ||||
8754 | ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, | |||
8755 | bool IsImplicit = false); | |||
8756 | ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, | |||
8757 | UnresolvedLookupExpr* Lookup); | |||
8758 | ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); | |||
8759 | StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, | |||
8760 | bool IsImplicit = false); | |||
8761 | StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); | |||
8762 | bool buildCoroutineParameterMoves(SourceLocation Loc); | |||
8763 | VarDecl *buildCoroutinePromise(SourceLocation Loc); | |||
8764 | void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); | |||
8765 | ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, | |||
8766 | SourceLocation FuncLoc); | |||
8767 | ||||
8768 | //===--------------------------------------------------------------------===// | |||
8769 | // OpenCL extensions. | |||
8770 | // | |||
8771 | private: | |||
8772 | std::string CurrOpenCLExtension; | |||
8773 | /// Extensions required by an OpenCL type. | |||
8774 | llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; | |||
8775 | /// Extensions required by an OpenCL declaration. | |||
8776 | llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; | |||
8777 | public: | |||
8778 | llvm::StringRef getCurrentOpenCLExtension() const { | |||
8779 | return CurrOpenCLExtension; | |||
8780 | } | |||
8781 | ||||
8782 | /// Check if a function declaration \p FD associates with any | |||
8783 | /// extensions present in OpenCLDeclExtMap and if so return the | |||
8784 | /// extension(s) name(s). | |||
8785 | std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); | |||
8786 | ||||
8787 | /// Check if a function type \p FT associates with any | |||
8788 | /// extensions present in OpenCLTypeExtMap and if so return the | |||
8789 | /// extension(s) name(s). | |||
8790 | std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); | |||
8791 | ||||
8792 | /// Find an extension in an appropriate extension map and return its name | |||
8793 | template<typename T, typename MapT> | |||
8794 | std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); | |||
8795 | ||||
8796 | void setCurrentOpenCLExtension(llvm::StringRef Ext) { | |||
8797 | CurrOpenCLExtension = Ext; | |||
8798 | } | |||
8799 | ||||
8800 | /// Set OpenCL extensions for a type which can only be used when these | |||
8801 | /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. | |||
8802 | /// \param Exts A space separated list of OpenCL extensions. | |||
8803 | void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); | |||
8804 | ||||
8805 | /// Set OpenCL extensions for a declaration which can only be | |||
8806 | /// used when these OpenCL extensions are enabled. If \p Exts is empty, do | |||
8807 | /// nothing. | |||
8808 | /// \param Exts A space separated list of OpenCL extensions. | |||
8809 | void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); | |||
8810 | ||||
8811 | /// Set current OpenCL extensions for a type which can only be used | |||
8812 | /// when these OpenCL extensions are enabled. If current OpenCL extension is | |||
8813 | /// empty, do nothing. | |||
8814 | void setCurrentOpenCLExtensionForType(QualType T); | |||
8815 | ||||
8816 | /// Set current OpenCL extensions for a declaration which | |||
8817 | /// can only be used when these OpenCL extensions are enabled. If current | |||
8818 | /// OpenCL extension is empty, do nothing. | |||
8819 | void setCurrentOpenCLExtensionForDecl(Decl *FD); | |||
8820 | ||||
8821 | bool isOpenCLDisabledDecl(Decl *FD); | |||
8822 | ||||
8823 | /// Check if type \p T corresponding to declaration specifier \p DS | |||
8824 | /// is disabled due to required OpenCL extensions being disabled. If so, | |||
8825 | /// emit diagnostics. | |||
8826 | /// \return true if type is disabled. | |||
8827 | bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); | |||
8828 | ||||
8829 | /// Check if declaration \p D used by expression \p E | |||
8830 | /// is disabled due to required OpenCL extensions being disabled. If so, | |||
8831 | /// emit diagnostics. | |||
8832 | /// \return true if type is disabled. | |||
8833 | bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); | |||
8834 | ||||
8835 | //===--------------------------------------------------------------------===// | |||
8836 | // OpenMP directives and clauses. | |||
8837 | // | |||
8838 | private: | |||
8839 | void *VarDataSharingAttributesStack; | |||
8840 | /// Number of nested '#pragma omp declare target' directives. | |||
8841 | unsigned DeclareTargetNestingLevel = 0; | |||
8842 | /// Initialization of data-sharing attributes stack. | |||
8843 | void InitDataSharingAttributesStack(); | |||
8844 | void DestroyDataSharingAttributesStack(); | |||
8845 | ExprResult | |||
8846 | VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, | |||
8847 | bool StrictlyPositive = true); | |||
8848 | /// Returns OpenMP nesting level for current directive. | |||
8849 | unsigned getOpenMPNestingLevel() const; | |||
8850 | ||||
8851 | /// Adjusts the function scopes index for the target-based regions. | |||
8852 | void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, | |||
8853 | unsigned Level) const; | |||
8854 | ||||
8855 | /// Push new OpenMP function region for non-capturing function. | |||
8856 | void pushOpenMPFunctionRegion(); | |||
8857 | ||||
8858 | /// Pop OpenMP function region for non-capturing function. | |||
8859 | void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); | |||
8860 | ||||
8861 | /// Check whether we're allowed to call Callee from the current function. | |||
8862 | void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); | |||
8863 | ||||
8864 | /// Check if the expression is allowed to be used in expressions for the | |||
8865 | /// OpenMP devices. | |||
8866 | void checkOpenMPDeviceExpr(const Expr *E); | |||
8867 | ||||
8868 | /// Checks if a type or a declaration is disabled due to the owning extension | |||
8869 | /// being disabled, and emits diagnostic messages if it is disabled. | |||
8870 | /// \param D type or declaration to be checked. | |||
8871 | /// \param DiagLoc source location for the diagnostic message. | |||
8872 | /// \param DiagInfo information to be emitted for the diagnostic message. | |||
8873 | /// \param SrcRange source range of the declaration. | |||
8874 | /// \param Map maps type or declaration to the extensions. | |||
8875 | /// \param Selector selects diagnostic message: 0 for type and 1 for | |||
8876 | /// declaration. | |||
8877 | /// \return true if the type or declaration is disabled. | |||
8878 | template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> | |||
8879 | bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, | |||
8880 | MapT &Map, unsigned Selector = 0, | |||
8881 | SourceRange SrcRange = SourceRange()); | |||
8882 | ||||
8883 | public: | |||
8884 | /// Return true if the provided declaration \a VD should be captured by | |||
8885 | /// reference. | |||
8886 | /// \param Level Relative level of nested OpenMP construct for that the check | |||
8887 | /// is performed. | |||
8888 | bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const; | |||
8889 | ||||
8890 | /// Check if the specified variable is used in one of the private | |||
8891 | /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP | |||
8892 | /// constructs. | |||
8893 | VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, | |||
8894 | unsigned StopAt = 0); | |||
8895 | ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, | |||
8896 | ExprObjectKind OK, SourceLocation Loc); | |||
8897 | ||||
8898 | /// If the current region is a loop-based region, mark the start of the loop | |||
8899 | /// construct. | |||
8900 | void startOpenMPLoop(); | |||
8901 | ||||
8902 | /// Check if the specified variable is used in 'private' clause. | |||
8903 | /// \param Level Relative level of nested OpenMP construct for that the check | |||
8904 | /// is performed. | |||
8905 | bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; | |||
8906 | ||||
8907 | /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) | |||
8908 | /// for \p FD based on DSA for the provided corresponding captured declaration | |||
8909 | /// \p D. | |||
8910 | void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); | |||
8911 | ||||
8912 | /// Check if the specified variable is captured by 'target' directive. | |||
8913 | /// \param Level Relative level of nested OpenMP construct for that the check | |||
8914 | /// is performed. | |||
8915 | bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; | |||
8916 | ||||
8917 | ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, | |||
8918 | Expr *Op); | |||
8919 | /// Called on start of new data sharing attribute block. | |||
8920 | void StartOpenMPDSABlock(OpenMPDirectiveKind K, | |||
8921 | const DeclarationNameInfo &DirName, Scope *CurScope, | |||
8922 | SourceLocation Loc); | |||
8923 | /// Start analysis of clauses. | |||
8924 | void StartOpenMPClause(OpenMPClauseKind K); | |||
8925 | /// End analysis of clauses. | |||
8926 | void EndOpenMPClause(); | |||
8927 | /// Called on end of data sharing attribute block. | |||
8928 | void EndOpenMPDSABlock(Stmt *CurDirective); | |||
8929 | ||||
8930 | /// Check if the current region is an OpenMP loop region and if it is, | |||
8931 | /// mark loop control variable, used in \p Init for loop initialization, as | |||
8932 | /// private by default. | |||
8933 | /// \param Init First part of the for loop. | |||
8934 | void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); | |||
8935 | ||||
8936 | // OpenMP directives and clauses. | |||
8937 | /// Called on correct id-expression from the '#pragma omp | |||
8938 | /// threadprivate'. | |||
8939 | ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, | |||
8940 | const DeclarationNameInfo &Id, | |||
8941 | OpenMPDirectiveKind Kind); | |||
8942 | /// Called on well-formed '#pragma omp threadprivate'. | |||
8943 | DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( | |||
8944 | SourceLocation Loc, | |||
8945 | ArrayRef<Expr *> VarList); | |||
8946 | /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. | |||
8947 | OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, | |||
8948 | ArrayRef<Expr *> VarList); | |||
8949 | /// Called on well-formed '#pragma omp allocate'. | |||
8950 | DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, | |||
8951 | ArrayRef<Expr *> VarList, | |||
8952 | ArrayRef<OMPClause *> Clauses, | |||
8953 | DeclContext *Owner = nullptr); | |||
8954 | /// Called on well-formed '#pragma omp requires'. | |||
8955 | DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, | |||
8956 | ArrayRef<OMPClause *> ClauseList); | |||
8957 | /// Check restrictions on Requires directive | |||
8958 | OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, | |||
8959 | ArrayRef<OMPClause *> Clauses); | |||
8960 | /// Check if the specified type is allowed to be used in 'omp declare | |||
8961 | /// reduction' construct. | |||
8962 | QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, | |||
8963 | TypeResult ParsedType); | |||
8964 | /// Called on start of '#pragma omp declare reduction'. | |||
8965 | DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( | |||
8966 | Scope *S, DeclContext *DC, DeclarationName Name, | |||
8967 | ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, | |||
8968 | AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); | |||
8969 | /// Initialize declare reduction construct initializer. | |||
8970 | void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); | |||
8971 | /// Finish current declare reduction construct initializer. | |||
8972 | void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); | |||
8973 | /// Initialize declare reduction construct initializer. | |||
8974 | /// \return omp_priv variable. | |||
8975 | VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); | |||
8976 | /// Finish current declare reduction construct initializer. | |||
8977 | void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, | |||
8978 | VarDecl *OmpPrivParm); | |||
8979 | /// Called at the end of '#pragma omp declare reduction'. | |||
8980 | DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( | |||
8981 | Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); | |||
8982 | ||||
8983 | /// Check variable declaration in 'omp declare mapper' construct. | |||
8984 | TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); | |||
8985 | /// Check if the specified type is allowed to be used in 'omp declare | |||
8986 | /// mapper' construct. | |||
8987 | QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, | |||
8988 | TypeResult ParsedType); | |||
8989 | /// Called on start of '#pragma omp declare mapper'. | |||
8990 | OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( | |||
8991 | Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, | |||
8992 | SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, | |||
8993 | Decl *PrevDeclInScope = nullptr); | |||
8994 | /// Build the mapper variable of '#pragma omp declare mapper'. | |||
8995 | void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, | |||
8996 | Scope *S, QualType MapperType, | |||
8997 | SourceLocation StartLoc, | |||
8998 | DeclarationName VN); | |||
8999 | /// Called at the end of '#pragma omp declare mapper'. | |||
9000 | DeclGroupPtrTy | |||
9001 | ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, | |||
9002 | ArrayRef<OMPClause *> ClauseList); | |||
9003 | ||||
9004 | /// Called on the start of target region i.e. '#pragma omp declare target'. | |||
9005 | bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); | |||
9006 | /// Called at the end of target region i.e. '#pragme omp end declare target'. | |||
9007 | void ActOnFinishOpenMPDeclareTargetDirective(); | |||
9008 | /// Called on correct id-expression from the '#pragma omp declare target'. | |||
9009 | void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, | |||
9010 | const DeclarationNameInfo &Id, | |||
9011 | OMPDeclareTargetDeclAttr::MapTypeTy MT, | |||
9012 | NamedDeclSetType &SameDirectiveDecls); | |||
9013 | /// Check declaration inside target region. | |||
9014 | void | |||
9015 | checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, | |||
9016 | SourceLocation IdLoc = SourceLocation()); | |||
9017 | /// Return true inside OpenMP declare target region. | |||
9018 | bool isInOpenMPDeclareTargetContext() const { | |||
9019 | return DeclareTargetNestingLevel > 0; | |||
9020 | } | |||
9021 | /// Return true inside OpenMP target region. | |||
9022 | bool isInOpenMPTargetExecutionDirective() const; | |||
9023 | /// Return true if (un)supported features for the current target should be | |||
9024 | /// diagnosed if OpenMP (offloading) is enabled. | |||
9025 | bool shouldDiagnoseTargetSupportFromOpenMP() const { | |||
9026 | return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() || | |||
9027 | isInOpenMPTargetExecutionDirective(); | |||
9028 | } | |||
9029 | ||||
9030 | /// Return the number of captured regions created for an OpenMP directive. | |||
9031 | static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); | |||
9032 | ||||
9033 | /// Initialization of captured region for OpenMP region. | |||
9034 | void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); | |||
9035 | /// End of OpenMP region. | |||
9036 | /// | |||
9037 | /// \param S Statement associated with the current OpenMP region. | |||
9038 | /// \param Clauses List of clauses for the current OpenMP region. | |||
9039 | /// | |||
9040 | /// \returns Statement for finished OpenMP region. | |||
9041 | StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); | |||
9042 | StmtResult ActOnOpenMPExecutableDirective( | |||
9043 | OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, | |||
9044 | OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, | |||
9045 | Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); | |||
9046 | /// Called on well-formed '\#pragma omp parallel' after parsing | |||
9047 | /// of the associated statement. | |||
9048 | StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, | |||
9049 | Stmt *AStmt, | |||
9050 | SourceLocation StartLoc, | |||
9051 | SourceLocation EndLoc); | |||
9052 | using VarsWithInheritedDSAType = | |||
9053 | llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; | |||
9054 | /// Called on well-formed '\#pragma omp simd' after parsing | |||
9055 | /// of the associated statement. | |||
9056 | StmtResult | |||
9057 | ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, | |||
9058 | SourceLocation StartLoc, SourceLocation EndLoc, | |||
9059 | VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9060 | /// Called on well-formed '\#pragma omp for' after parsing | |||
9061 | /// of the associated statement. | |||
9062 | StmtResult | |||
9063 | ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, | |||
9064 | SourceLocation StartLoc, SourceLocation EndLoc, | |||
9065 | VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9066 | /// Called on well-formed '\#pragma omp for simd' after parsing | |||
9067 | /// of the associated statement. | |||
9068 | StmtResult | |||
9069 | ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, | |||
9070 | SourceLocation StartLoc, SourceLocation EndLoc, | |||
9071 | VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9072 | /// Called on well-formed '\#pragma omp sections' after parsing | |||
9073 | /// of the associated statement. | |||
9074 | StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, | |||
9075 | Stmt *AStmt, SourceLocation StartLoc, | |||
9076 | SourceLocation EndLoc); | |||
9077 | /// Called on well-formed '\#pragma omp section' after parsing of the | |||
9078 | /// associated statement. | |||
9079 | StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, | |||
9080 | SourceLocation EndLoc); | |||
9081 | /// Called on well-formed '\#pragma omp single' after parsing of the | |||
9082 | /// associated statement. | |||
9083 | StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, | |||
9084 | Stmt *AStmt, SourceLocation StartLoc, | |||
9085 | SourceLocation EndLoc); | |||
9086 | /// Called on well-formed '\#pragma omp master' after parsing of the | |||
9087 | /// associated statement. | |||
9088 | StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, | |||
9089 | SourceLocation EndLoc); | |||
9090 | /// Called on well-formed '\#pragma omp critical' after parsing of the | |||
9091 | /// associated statement. | |||
9092 | StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, | |||
9093 | ArrayRef<OMPClause *> Clauses, | |||
9094 | Stmt *AStmt, SourceLocation StartLoc, | |||
9095 | SourceLocation EndLoc); | |||
9096 | /// Called on well-formed '\#pragma omp parallel for' after parsing | |||
9097 | /// of the associated statement. | |||
9098 | StmtResult ActOnOpenMPParallelForDirective( | |||
9099 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9100 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9101 | /// Called on well-formed '\#pragma omp parallel for simd' after | |||
9102 | /// parsing of the associated statement. | |||
9103 | StmtResult ActOnOpenMPParallelForSimdDirective( | |||
9104 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9105 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9106 | /// Called on well-formed '\#pragma omp parallel sections' after | |||
9107 | /// parsing of the associated statement. | |||
9108 | StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, | |||
9109 | Stmt *AStmt, | |||
9110 | SourceLocation StartLoc, | |||
9111 | SourceLocation EndLoc); | |||
9112 | /// Called on well-formed '\#pragma omp task' after parsing of the | |||
9113 | /// associated statement. | |||
9114 | StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, | |||
9115 | Stmt *AStmt, SourceLocation StartLoc, | |||
9116 | SourceLocation EndLoc); | |||
9117 | /// Called on well-formed '\#pragma omp taskyield'. | |||
9118 | StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, | |||
9119 | SourceLocation EndLoc); | |||
9120 | /// Called on well-formed '\#pragma omp barrier'. | |||
9121 | StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, | |||
9122 | SourceLocation EndLoc); | |||
9123 | /// Called on well-formed '\#pragma omp taskwait'. | |||
9124 | StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, | |||
9125 | SourceLocation EndLoc); | |||
9126 | /// Called on well-formed '\#pragma omp taskgroup'. | |||
9127 | StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, | |||
9128 | Stmt *AStmt, SourceLocation StartLoc, | |||
9129 | SourceLocation EndLoc); | |||
9130 | /// Called on well-formed '\#pragma omp flush'. | |||
9131 | StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, | |||
9132 | SourceLocation StartLoc, | |||
9133 | SourceLocation EndLoc); | |||
9134 | /// Called on well-formed '\#pragma omp ordered' after parsing of the | |||
9135 | /// associated statement. | |||
9136 | StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, | |||
9137 | Stmt *AStmt, SourceLocation StartLoc, | |||
9138 | SourceLocation EndLoc); | |||
9139 | /// Called on well-formed '\#pragma omp atomic' after parsing of the | |||
9140 | /// associated statement. | |||
9141 | StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, | |||
9142 | Stmt *AStmt, SourceLocation StartLoc, | |||
9143 | SourceLocation EndLoc); | |||
9144 | /// Called on well-formed '\#pragma omp target' after parsing of the | |||
9145 | /// associated statement. | |||
9146 | StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, | |||
9147 | Stmt *AStmt, SourceLocation StartLoc, | |||
9148 | SourceLocation EndLoc); | |||
9149 | /// Called on well-formed '\#pragma omp target data' after parsing of | |||
9150 | /// the associated statement. | |||
9151 | StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, | |||
9152 | Stmt *AStmt, SourceLocation StartLoc, | |||
9153 | SourceLocation EndLoc); | |||
9154 | /// Called on well-formed '\#pragma omp target enter data' after | |||
9155 | /// parsing of the associated statement. | |||
9156 | StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, | |||
9157 | SourceLocation StartLoc, | |||
9158 | SourceLocation EndLoc, | |||
9159 | Stmt *AStmt); | |||
9160 | /// Called on well-formed '\#pragma omp target exit data' after | |||
9161 | /// parsing of the associated statement. | |||
9162 | StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, | |||
9163 | SourceLocation StartLoc, | |||
9164 | SourceLocation EndLoc, | |||
9165 | Stmt *AStmt); | |||
9166 | /// Called on well-formed '\#pragma omp target parallel' after | |||
9167 | /// parsing of the associated statement. | |||
9168 | StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, | |||
9169 | Stmt *AStmt, | |||
9170 | SourceLocation StartLoc, | |||
9171 | SourceLocation EndLoc); | |||
9172 | /// Called on well-formed '\#pragma omp target parallel for' after | |||
9173 | /// parsing of the associated statement. | |||
9174 | StmtResult ActOnOpenMPTargetParallelForDirective( | |||
9175 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9176 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9177 | /// Called on well-formed '\#pragma omp teams' after parsing of the | |||
9178 | /// associated statement. | |||
9179 | StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, | |||
9180 | Stmt *AStmt, SourceLocation StartLoc, | |||
9181 | SourceLocation EndLoc); | |||
9182 | /// Called on well-formed '\#pragma omp cancellation point'. | |||
9183 | StmtResult | |||
9184 | ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, | |||
9185 | SourceLocation EndLoc, | |||
9186 | OpenMPDirectiveKind CancelRegion); | |||
9187 | /// Called on well-formed '\#pragma omp cancel'. | |||
9188 | StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, | |||
9189 | SourceLocation StartLoc, | |||
9190 | SourceLocation EndLoc, | |||
9191 | OpenMPDirectiveKind CancelRegion); | |||
9192 | /// Called on well-formed '\#pragma omp taskloop' after parsing of the | |||
9193 | /// associated statement. | |||
9194 | StmtResult | |||
9195 | ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, | |||
9196 | SourceLocation StartLoc, SourceLocation EndLoc, | |||
9197 | VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9198 | /// Called on well-formed '\#pragma omp taskloop simd' after parsing of | |||
9199 | /// the associated statement. | |||
9200 | StmtResult ActOnOpenMPTaskLoopSimdDirective( | |||
9201 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9202 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9203 | /// Called on well-formed '\#pragma omp distribute' after parsing | |||
9204 | /// of the associated statement. | |||
9205 | StmtResult | |||
9206 | ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, | |||
9207 | SourceLocation StartLoc, SourceLocation EndLoc, | |||
9208 | VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9209 | /// Called on well-formed '\#pragma omp target update'. | |||
9210 | StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, | |||
9211 | SourceLocation StartLoc, | |||
9212 | SourceLocation EndLoc, | |||
9213 | Stmt *AStmt); | |||
9214 | /// Called on well-formed '\#pragma omp distribute parallel for' after | |||
9215 | /// parsing of the associated statement. | |||
9216 | StmtResult ActOnOpenMPDistributeParallelForDirective( | |||
9217 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9218 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9219 | /// Called on well-formed '\#pragma omp distribute parallel for simd' | |||
9220 | /// after parsing of the associated statement. | |||
9221 | StmtResult ActOnOpenMPDistributeParallelForSimdDirective( | |||
9222 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9223 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9224 | /// Called on well-formed '\#pragma omp distribute simd' after | |||
9225 | /// parsing of the associated statement. | |||
9226 | StmtResult ActOnOpenMPDistributeSimdDirective( | |||
9227 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9228 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9229 | /// Called on well-formed '\#pragma omp target parallel for simd' after | |||
9230 | /// parsing of the associated statement. | |||
9231 | StmtResult ActOnOpenMPTargetParallelForSimdDirective( | |||
9232 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9233 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9234 | /// Called on well-formed '\#pragma omp target simd' after parsing of | |||
9235 | /// the associated statement. | |||
9236 | StmtResult | |||
9237 | ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, | |||
9238 | SourceLocation StartLoc, SourceLocation EndLoc, | |||
9239 | VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9240 | /// Called on well-formed '\#pragma omp teams distribute' after parsing of | |||
9241 | /// the associated statement. | |||
9242 | StmtResult ActOnOpenMPTeamsDistributeDirective( | |||
9243 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9244 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9245 | /// Called on well-formed '\#pragma omp teams distribute simd' after parsing | |||
9246 | /// of the associated statement. | |||
9247 | StmtResult ActOnOpenMPTeamsDistributeSimdDirective( | |||
9248 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9249 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9250 | /// Called on well-formed '\#pragma omp teams distribute parallel for simd' | |||
9251 | /// after parsing of the associated statement. | |||
9252 | StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( | |||
9253 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9254 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9255 | /// Called on well-formed '\#pragma omp teams distribute parallel for' | |||
9256 | /// after parsing of the associated statement. | |||
9257 | StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( | |||
9258 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9259 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9260 | /// Called on well-formed '\#pragma omp target teams' after parsing of the | |||
9261 | /// associated statement. | |||
9262 | StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, | |||
9263 | Stmt *AStmt, | |||
9264 | SourceLocation StartLoc, | |||
9265 | SourceLocation EndLoc); | |||
9266 | /// Called on well-formed '\#pragma omp target teams distribute' after parsing | |||
9267 | /// of the associated statement. | |||
9268 | StmtResult ActOnOpenMPTargetTeamsDistributeDirective( | |||
9269 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9270 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9271 | /// Called on well-formed '\#pragma omp target teams distribute parallel for' | |||
9272 | /// after parsing of the associated statement. | |||
9273 | StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( | |||
9274 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9275 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9276 | /// Called on well-formed '\#pragma omp target teams distribute parallel for | |||
9277 | /// simd' after parsing of the associated statement. | |||
9278 | StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( | |||
9279 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9280 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9281 | /// Called on well-formed '\#pragma omp target teams distribute simd' after | |||
9282 | /// parsing of the associated statement. | |||
9283 | StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( | |||
9284 | ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, | |||
9285 | SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); | |||
9286 | ||||
9287 | /// Checks correctness of linear modifiers. | |||
9288 | bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, | |||
9289 | SourceLocation LinLoc); | |||
9290 | /// Checks that the specified declaration matches requirements for the linear | |||
9291 | /// decls. | |||
9292 | bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, | |||
9293 | OpenMPLinearClauseKind LinKind, QualType Type); | |||
9294 | ||||
9295 | /// Called on well-formed '\#pragma omp declare simd' after parsing of | |||
9296 | /// the associated method/function. | |||
9297 | DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( | |||
9298 | DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, | |||
9299 | Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, | |||
9300 | ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, | |||
9301 | ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); | |||
9302 | ||||
9303 | OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, | |||
9304 | Expr *Expr, | |||
9305 | SourceLocation StartLoc, | |||
9306 | SourceLocation LParenLoc, | |||
9307 | SourceLocation EndLoc); | |||
9308 | /// Called on well-formed 'allocator' clause. | |||
9309 | OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, | |||
9310 | SourceLocation StartLoc, | |||
9311 | SourceLocation LParenLoc, | |||
9312 | SourceLocation EndLoc); | |||
9313 | /// Called on well-formed 'if' clause. | |||
9314 | OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, | |||
9315 | Expr *Condition, SourceLocation StartLoc, | |||
9316 | SourceLocation LParenLoc, | |||
9317 | SourceLocation NameModifierLoc, | |||
9318 | SourceLocation ColonLoc, | |||
9319 | SourceLocation EndLoc); | |||
9320 | /// Called on well-formed 'final' clause. | |||
9321 | OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, | |||
9322 | SourceLocation LParenLoc, | |||
9323 | SourceLocation EndLoc); | |||
9324 | /// Called on well-formed 'num_threads' clause. | |||
9325 | OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, | |||
9326 | SourceLocation StartLoc, | |||
9327 | SourceLocation LParenLoc, | |||
9328 | SourceLocation EndLoc); | |||
9329 | /// Called on well-formed 'safelen' clause. | |||
9330 | OMPClause *ActOnOpenMPSafelenClause(Expr *Length, | |||
9331 | SourceLocation StartLoc, | |||
9332 | SourceLocation LParenLoc, | |||
9333 | SourceLocation EndLoc); | |||
9334 | /// Called on well-formed 'simdlen' clause. | |||
9335 | OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, | |||
9336 | SourceLocation LParenLoc, | |||
9337 | SourceLocation EndLoc); | |||
9338 | /// Called on well-formed 'collapse' clause. | |||
9339 | OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, | |||
9340 | SourceLocation StartLoc, | |||
9341 | SourceLocation LParenLoc, | |||
9342 | SourceLocation EndLoc); | |||
9343 | /// Called on well-formed 'ordered' clause. | |||
9344 | OMPClause * | |||
9345 | ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, | |||
9346 | SourceLocation LParenLoc = SourceLocation(), | |||
9347 | Expr *NumForLoops = nullptr); | |||
9348 | /// Called on well-formed 'grainsize' clause. | |||
9349 | OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, | |||
9350 | SourceLocation LParenLoc, | |||
9351 | SourceLocation EndLoc); | |||
9352 | /// Called on well-formed 'num_tasks' clause. | |||
9353 | OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, | |||
9354 | SourceLocation LParenLoc, | |||
9355 | SourceLocation EndLoc); | |||
9356 | /// Called on well-formed 'hint' clause. | |||
9357 | OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, | |||
9358 | SourceLocation LParenLoc, | |||
9359 | SourceLocation EndLoc); | |||
9360 | ||||
9361 | OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, | |||
9362 | unsigned Argument, | |||
9363 | SourceLocation ArgumentLoc, | |||
9364 | SourceLocation StartLoc, | |||
9365 | SourceLocation LParenLoc, | |||
9366 | SourceLocation EndLoc); | |||
9367 | /// Called on well-formed 'default' clause. | |||
9368 | OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, | |||
9369 | SourceLocation KindLoc, | |||
9370 | SourceLocation StartLoc, | |||
9371 | SourceLocation LParenLoc, | |||
9372 | SourceLocation EndLoc); | |||
9373 | /// Called on well-formed 'proc_bind' clause. | |||
9374 | OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, | |||
9375 | SourceLocation KindLoc, | |||
9376 | SourceLocation StartLoc, | |||
9377 | SourceLocation LParenLoc, | |||
9378 | SourceLocation EndLoc); | |||
9379 | ||||
9380 | OMPClause *ActOnOpenMPSingleExprWithArgClause( | |||
9381 | OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, | |||
9382 | SourceLocation StartLoc, SourceLocation LParenLoc, | |||
9383 | ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, | |||
9384 | SourceLocation EndLoc); | |||
9385 | /// Called on well-formed 'schedule' clause. | |||
9386 | OMPClause *ActOnOpenMPScheduleClause( | |||
9387 | OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, | |||
9388 | OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, | |||
9389 | SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, | |||
9390 | SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); | |||
9391 | ||||
9392 | OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, | |||
9393 | SourceLocation EndLoc); | |||
9394 | /// Called on well-formed 'nowait' clause. | |||
9395 | OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, | |||
9396 | SourceLocation EndLoc); | |||
9397 | /// Called on well-formed 'untied' clause. | |||
9398 | OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, | |||
9399 | SourceLocation EndLoc); | |||
9400 | /// Called on well-formed 'mergeable' clause. | |||
9401 | OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, | |||
9402 | SourceLocation EndLoc); | |||
9403 | /// Called on well-formed 'read' clause. | |||
9404 | OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, | |||
9405 | SourceLocation EndLoc); | |||
9406 | /// Called on well-formed 'write' clause. | |||
9407 | OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, | |||
9408 | SourceLocation EndLoc); | |||
9409 | /// Called on well-formed 'update' clause. | |||
9410 | OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, | |||
9411 | SourceLocation EndLoc); | |||
9412 | /// Called on well-formed 'capture' clause. | |||
9413 | OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, | |||
9414 | SourceLocation EndLoc); | |||
9415 | /// Called on well-formed 'seq_cst' clause. | |||
9416 | OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, | |||
9417 | SourceLocation EndLoc); | |||
9418 | /// Called on well-formed 'threads' clause. | |||
9419 | OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, | |||
9420 | SourceLocation EndLoc); | |||
9421 | /// Called on well-formed 'simd' clause. | |||
9422 | OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, | |||
9423 | SourceLocation EndLoc); | |||
9424 | /// Called on well-formed 'nogroup' clause. | |||
9425 | OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, | |||
9426 | SourceLocation EndLoc); | |||
9427 | /// Called on well-formed 'unified_address' clause. | |||
9428 | OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, | |||
9429 | SourceLocation EndLoc); | |||
9430 | ||||
9431 | /// Called on well-formed 'unified_address' clause. | |||
9432 | OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, | |||
9433 | SourceLocation EndLoc); | |||
9434 | ||||
9435 | /// Called on well-formed 'reverse_offload' clause. | |||
9436 | OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, | |||
9437 | SourceLocation EndLoc); | |||
9438 | ||||
9439 | /// Called on well-formed 'dynamic_allocators' clause. | |||
9440 | OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, | |||
9441 | SourceLocation EndLoc); | |||
9442 | ||||
9443 | /// Called on well-formed 'atomic_default_mem_order' clause. | |||
9444 | OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( | |||
9445 | OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, | |||
9446 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); | |||
9447 | ||||
9448 | OMPClause *ActOnOpenMPVarListClause( | |||
9449 | OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, | |||
9450 | const OMPVarListLocTy &Locs, SourceLocation ColonLoc, | |||
9451 | CXXScopeSpec &ReductionOrMapperIdScopeSpec, | |||
9452 | DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind, | |||
9453 | OpenMPLinearClauseKind LinKind, | |||
9454 | ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, | |||
9455 | ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, | |||
9456 | bool IsMapTypeImplicit, SourceLocation DepLinMapLoc); | |||
9457 | /// Called on well-formed 'allocate' clause. | |||
9458 | OMPClause * | |||
9459 | ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, | |||
9460 | SourceLocation StartLoc, SourceLocation ColonLoc, | |||
9461 | SourceLocation LParenLoc, SourceLocation EndLoc); | |||
9462 | /// Called on well-formed 'private' clause. | |||
9463 | OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, | |||
9464 | SourceLocation StartLoc, | |||
9465 | SourceLocation LParenLoc, | |||
9466 | SourceLocation EndLoc); | |||
9467 | /// Called on well-formed 'firstprivate' clause. | |||
9468 | OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, | |||
9469 | SourceLocation StartLoc, | |||
9470 | SourceLocation LParenLoc, | |||
9471 | SourceLocation EndLoc); | |||
9472 | /// Called on well-formed 'lastprivate' clause. | |||
9473 | OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, | |||
9474 | SourceLocation StartLoc, | |||
9475 | SourceLocation LParenLoc, | |||
9476 | SourceLocation EndLoc); | |||
9477 | /// Called on well-formed 'shared' clause. | |||
9478 | OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, | |||
9479 | SourceLocation StartLoc, | |||
9480 | SourceLocation LParenLoc, | |||
9481 | SourceLocation EndLoc); | |||
9482 | /// Called on well-formed 'reduction' clause. | |||
9483 | OMPClause *ActOnOpenMPReductionClause( | |||
9484 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, | |||
9485 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, | |||
9486 | CXXScopeSpec &ReductionIdScopeSpec, | |||
9487 | const DeclarationNameInfo &ReductionId, | |||
9488 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); | |||
9489 | /// Called on well-formed 'task_reduction' clause. | |||
9490 | OMPClause *ActOnOpenMPTaskReductionClause( | |||
9491 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, | |||
9492 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, | |||
9493 | CXXScopeSpec &ReductionIdScopeSpec, | |||
9494 | const DeclarationNameInfo &ReductionId, | |||
9495 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); | |||
9496 | /// Called on well-formed 'in_reduction' clause. | |||
9497 | OMPClause *ActOnOpenMPInReductionClause( | |||
9498 | ArrayRef<Expr *> VarList, SourceLocation StartLoc, | |||
9499 | SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, | |||
9500 | CXXScopeSpec &ReductionIdScopeSpec, | |||
9501 | const DeclarationNameInfo &ReductionId, | |||
9502 | ArrayRef<Expr *> UnresolvedReductions = llvm::None); | |||
9503 | /// Called on well-formed 'linear' clause. | |||
9504 | OMPClause * | |||
9505 | ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, | |||
9506 | SourceLocation StartLoc, SourceLocation LParenLoc, | |||
9507 | OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, | |||
9508 | SourceLocation ColonLoc, SourceLocation EndLoc); | |||
9509 | /// Called on well-formed 'aligned' clause. | |||
9510 | OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, | |||
9511 | Expr *Alignment, | |||
9512 | SourceLocation StartLoc, | |||
9513 | SourceLocation LParenLoc, | |||
9514 | SourceLocation ColonLoc, | |||
9515 | SourceLocation EndLoc); | |||
9516 | /// Called on well-formed 'copyin' clause. | |||
9517 | OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, | |||
9518 | SourceLocation StartLoc, | |||
9519 | SourceLocation LParenLoc, | |||
9520 | SourceLocation EndLoc); | |||
9521 | /// Called on well-formed 'copyprivate' clause. | |||
9522 | OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, | |||
9523 | SourceLocation StartLoc, | |||
9524 | SourceLocation LParenLoc, | |||
9525 | SourceLocation EndLoc); | |||
9526 | /// Called on well-formed 'flush' pseudo clause. | |||
9527 | OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, | |||
9528 | SourceLocation StartLoc, | |||
9529 | SourceLocation LParenLoc, | |||
9530 | SourceLocation EndLoc); | |||
9531 | /// Called on well-formed 'depend' clause. | |||
9532 | OMPClause * | |||
9533 | ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, | |||
9534 | SourceLocation ColonLoc, ArrayRef<Expr *> VarList, | |||
9535 | SourceLocation StartLoc, SourceLocation LParenLoc, | |||
9536 | SourceLocation EndLoc); | |||
9537 | /// Called on well-formed 'device' clause. | |||
9538 | OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, | |||
9539 | SourceLocation LParenLoc, | |||
9540 | SourceLocation EndLoc); | |||
9541 | /// Called on well-formed 'map' clause. | |||
9542 | OMPClause * | |||
9543 | ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, | |||
9544 | ArrayRef<SourceLocation> MapTypeModifiersLoc, | |||
9545 | CXXScopeSpec &MapperIdScopeSpec, | |||
9546 | DeclarationNameInfo &MapperId, | |||
9547 | OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, | |||
9548 | SourceLocation MapLoc, SourceLocation ColonLoc, | |||
9549 | ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, | |||
9550 | ArrayRef<Expr *> UnresolvedMappers = llvm::None); | |||
9551 | /// Called on well-formed 'num_teams' clause. | |||
9552 | OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, | |||
9553 | SourceLocation LParenLoc, | |||
9554 | SourceLocation EndLoc); | |||
9555 | /// Called on well-formed 'thread_limit' clause. | |||
9556 | OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, | |||
9557 | SourceLocation StartLoc, | |||
9558 | SourceLocation LParenLoc, | |||
9559 | SourceLocation EndLoc); | |||
9560 | /// Called on well-formed 'priority' clause. | |||
9561 | OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, | |||
9562 | SourceLocation LParenLoc, | |||
9563 | SourceLocation EndLoc); | |||
9564 | /// Called on well-formed 'dist_schedule' clause. | |||
9565 | OMPClause *ActOnOpenMPDistScheduleClause( | |||
9566 | OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, | |||
9567 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, | |||
9568 | SourceLocation CommaLoc, SourceLocation EndLoc); | |||
9569 | /// Called on well-formed 'defaultmap' clause. | |||
9570 | OMPClause *ActOnOpenMPDefaultmapClause( | |||
9571 | OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, | |||
9572 | SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, | |||
9573 | SourceLocation KindLoc, SourceLocation EndLoc); | |||
9574 | /// Called on well-formed 'to' clause. | |||
9575 | OMPClause * | |||
9576 | ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, | |||
9577 | DeclarationNameInfo &MapperId, | |||
9578 | const OMPVarListLocTy &Locs, | |||
9579 | ArrayRef<Expr *> UnresolvedMappers = llvm::None); | |||
9580 | /// Called on well-formed 'from' clause. | |||
9581 | OMPClause *ActOnOpenMPFromClause( | |||
9582 | ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, | |||
9583 | DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, | |||
9584 | ArrayRef<Expr *> UnresolvedMappers = llvm::None); | |||
9585 | /// Called on well-formed 'use_device_ptr' clause. | |||
9586 | OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, | |||
9587 | const OMPVarListLocTy &Locs); | |||
9588 | /// Called on well-formed 'is_device_ptr' clause. | |||
9589 | OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, | |||
9590 | const OMPVarListLocTy &Locs); | |||
9591 | ||||
9592 | /// The kind of conversion being performed. | |||
9593 | enum CheckedConversionKind { | |||
9594 | /// An implicit conversion. | |||
9595 | CCK_ImplicitConversion, | |||
9596 | /// A C-style cast. | |||
9597 | CCK_CStyleCast, | |||
9598 | /// A functional-style cast. | |||
9599 | CCK_FunctionalCast, | |||
9600 | /// A cast other than a C-style cast. | |||
9601 | CCK_OtherCast, | |||
9602 | /// A conversion for an operand of a builtin overloaded operator. | |||
9603 | CCK_ForBuiltinOverloadedOp | |||
9604 | }; | |||
9605 | ||||
9606 | static bool isCast(CheckedConversionKind CCK) { | |||
9607 | return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || | |||
9608 | CCK == CCK_OtherCast; | |||
9609 | } | |||
9610 | ||||
9611 | /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit | |||
9612 | /// cast. If there is already an implicit cast, merge into the existing one. | |||
9613 | /// If isLvalue, the result of the cast is an lvalue. | |||
9614 | ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, | |||
9615 | ExprValueKind VK = VK_RValue, | |||
9616 | const CXXCastPath *BasePath = nullptr, | |||
9617 | CheckedConversionKind CCK | |||
9618 | = CCK_ImplicitConversion); | |||
9619 | ||||
9620 | /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding | |||
9621 | /// to the conversion from scalar type ScalarTy to the Boolean type. | |||
9622 | static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); | |||
9623 | ||||
9624 | /// IgnoredValueConversions - Given that an expression's result is | |||
9625 | /// syntactically ignored, perform any conversions that are | |||
9626 | /// required. | |||
9627 | ExprResult IgnoredValueConversions(Expr *E); | |||
9628 | ||||
9629 | // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts | |||
9630 | // functions and arrays to their respective pointers (C99 6.3.2.1). | |||
9631 | ExprResult UsualUnaryConversions(Expr *E); | |||
9632 | ||||
9633 | /// CallExprUnaryConversions - a special case of an unary conversion | |||
9634 | /// performed on a function designator of a call expression. | |||
9635 | ExprResult CallExprUnaryConversions(Expr *E); | |||
9636 | ||||
9637 | // DefaultFunctionArrayConversion - converts functions and arrays | |||
9638 | // to their respective pointers (C99 6.3.2.1). | |||
9639 | ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); | |||
9640 | ||||
9641 | // DefaultFunctionArrayLvalueConversion - converts functions and | |||
9642 | // arrays to their respective pointers and performs the | |||
9643 | // lvalue-to-rvalue conversion. | |||
9644 | ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, | |||
9645 | bool Diagnose = true); | |||
9646 | ||||
9647 | // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on | |||
9648 | // the operand. This is DefaultFunctionArrayLvalueConversion, | |||
9649 | // except that it assumes the operand isn't of function or array | |||
9650 | // type. | |||
9651 | ExprResult DefaultLvalueConversion(Expr *E); | |||
9652 | ||||
9653 | // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that | |||
9654 | // do not have a prototype. Integer promotions are performed on each | |||
9655 | // argument, and arguments that have type float are promoted to double. | |||
9656 | ExprResult DefaultArgumentPromotion(Expr *E); | |||
9657 | ||||
9658 | /// If \p E is a prvalue denoting an unmaterialized temporary, materialize | |||
9659 | /// it as an xvalue. In C++98, the result will still be a prvalue, because | |||
9660 | /// we don't have xvalues there. | |||
9661 | ExprResult TemporaryMaterializationConversion(Expr *E); | |||
9662 | ||||
9663 | // Used for emitting the right warning by DefaultVariadicArgumentPromotion | |||
9664 | enum VariadicCallType { | |||
9665 | VariadicFunction, | |||
9666 | VariadicBlock, | |||
9667 | VariadicMethod, | |||
9668 | VariadicConstructor, | |||
9669 | VariadicDoesNotApply | |||
9670 | }; | |||
9671 | ||||
9672 | VariadicCallType getVariadicCallType(FunctionDecl *FDecl, | |||
9673 | const FunctionProtoType *Proto, | |||
9674 | Expr *Fn); | |||
9675 | ||||
9676 | // Used for determining in which context a type is allowed to be passed to a | |||
9677 | // vararg function. | |||
9678 | enum VarArgKind { | |||
9679 | VAK_Valid, | |||
9680 | VAK_ValidInCXX11, | |||
9681 | VAK_Undefined, | |||
9682 | VAK_MSVCUndefined, | |||
9683 | VAK_Invalid | |||
9684 | }; | |||
9685 | ||||
9686 | // Determines which VarArgKind fits an expression. | |||
9687 | VarArgKind isValidVarArgType(const QualType &Ty); | |||
9688 | ||||
9689 | /// Check to see if the given expression is a valid argument to a variadic | |||
9690 | /// function, issuing a diagnostic if not. | |||
9691 | void checkVariadicArgument(const Expr *E, VariadicCallType CT); | |||
9692 | ||||
9693 | /// Check to see if a given expression could have '.c_str()' called on it. | |||
9694 | bool hasCStrMethod(const Expr *E); | |||
9695 | ||||
9696 | /// GatherArgumentsForCall - Collector argument expressions for various | |||
9697 | /// form of call prototypes. | |||
9698 | bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, | |||
9699 | const FunctionProtoType *Proto, | |||
9700 | unsigned FirstParam, ArrayRef<Expr *> Args, | |||
9701 | SmallVectorImpl<Expr *> &AllArgs, | |||
9702 | VariadicCallType CallType = VariadicDoesNotApply, | |||
9703 | bool AllowExplicit = false, | |||
9704 | bool IsListInitialization = false); | |||
9705 | ||||
9706 | // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but | |||
9707 | // will create a runtime trap if the resulting type is not a POD type. | |||
9708 | ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, | |||
9709 | FunctionDecl *FDecl); | |||
9710 | ||||
9711 | // UsualArithmeticConversions - performs the UsualUnaryConversions on it's | |||
9712 | // operands and then handles various conversions that are common to binary | |||
9713 | // operators (C99 6.3.1.8). If both operands aren't arithmetic, this | |||
9714 | // routine returns the first non-arithmetic type found. The client is | |||
9715 | // responsible for emitting appropriate error diagnostics. | |||
9716 | QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, | |||
9717 | bool IsCompAssign = false); | |||
9718 | ||||
9719 | /// AssignConvertType - All of the 'assignment' semantic checks return this | |||
9720 | /// enum to indicate whether the assignment was allowed. These checks are | |||
9721 | /// done for simple assignments, as well as initialization, return from | |||
9722 | /// function, argument passing, etc. The query is phrased in terms of a | |||
9723 | /// source and destination type. | |||
9724 | enum AssignConvertType { | |||
9725 | /// Compatible - the types are compatible according to the standard. | |||
9726 | Compatible, | |||
9727 | ||||
9728 | /// PointerToInt - The assignment converts a pointer to an int, which we | |||
9729 | /// accept as an extension. | |||
9730 | PointerToInt, | |||
9731 | ||||
9732 | /// IntToPointer - The assignment converts an int to a pointer, which we | |||
9733 | /// accept as an extension. | |||
9734 | IntToPointer, | |||
9735 | ||||
9736 | /// FunctionVoidPointer - The assignment is between a function pointer and | |||
9737 | /// void*, which the standard doesn't allow, but we accept as an extension. | |||
9738 | FunctionVoidPointer, | |||
9739 | ||||
9740 | /// IncompatiblePointer - The assignment is between two pointers types that | |||
9741 | /// are not compatible, but we accept them as an extension. | |||
9742 | IncompatiblePointer, | |||
9743 | ||||
9744 | /// IncompatiblePointerSign - The assignment is between two pointers types | |||
9745 | /// which point to integers which have a different sign, but are otherwise | |||
9746 | /// identical. This is a subset of the above, but broken out because it's by | |||
9747 | /// far the most common case of incompatible pointers. | |||
9748 | IncompatiblePointerSign, | |||
9749 | ||||
9750 | /// CompatiblePointerDiscardsQualifiers - The assignment discards | |||
9751 | /// c/v/r qualifiers, which we accept as an extension. | |||
9752 | CompatiblePointerDiscardsQualifiers, | |||
9753 | ||||
9754 | /// IncompatiblePointerDiscardsQualifiers - The assignment | |||
9755 | /// discards qualifiers that we don't permit to be discarded, | |||
9756 | /// like address spaces. | |||
9757 | IncompatiblePointerDiscardsQualifiers, | |||
9758 | ||||
9759 | /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment | |||
9760 | /// changes address spaces in nested pointer types which is not allowed. | |||
9761 | /// For instance, converting __private int ** to __generic int ** is | |||
9762 | /// illegal even though __private could be converted to __generic. | |||
9763 | IncompatibleNestedPointerAddressSpaceMismatch, | |||
9764 | ||||
9765 | /// IncompatibleNestedPointerQualifiers - The assignment is between two | |||
9766 | /// nested pointer types, and the qualifiers other than the first two | |||
9767 | /// levels differ e.g. char ** -> const char **, but we accept them as an | |||
9768 | /// extension. | |||
9769 | IncompatibleNestedPointerQualifiers, | |||
9770 | ||||
9771 | /// IncompatibleVectors - The assignment is between two vector types that | |||
9772 | /// have the same size, which we accept as an extension. | |||
9773 | IncompatibleVectors, | |||
9774 | ||||
9775 | /// IntToBlockPointer - The assignment converts an int to a block | |||
9776 | /// pointer. We disallow this. | |||
9777 | IntToBlockPointer, | |||
9778 | ||||
9779 | /// IncompatibleBlockPointer - The assignment is between two block | |||
9780 | /// pointers types that are not compatible. | |||
9781 | IncompatibleBlockPointer, | |||
9782 | ||||
9783 | /// IncompatibleObjCQualifiedId - The assignment is between a qualified | |||
9784 | /// id type and something else (that is incompatible with it). For example, | |||
9785 | /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. | |||
9786 | IncompatibleObjCQualifiedId, | |||
9787 | ||||
9788 | /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an | |||
9789 | /// object with __weak qualifier. | |||
9790 | IncompatibleObjCWeakRef, | |||
9791 | ||||
9792 | /// Incompatible - We reject this conversion outright, it is invalid to | |||
9793 | /// represent it in the AST. | |||
9794 | Incompatible | |||
9795 | }; | |||
9796 | ||||
9797 | /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the | |||
9798 | /// assignment conversion type specified by ConvTy. This returns true if the | |||
9799 | /// conversion was invalid or false if the conversion was accepted. | |||
9800 | bool DiagnoseAssignmentResult(AssignConvertType ConvTy, | |||
9801 | SourceLocation Loc, | |||
9802 | QualType DstType, QualType SrcType, | |||
9803 | Expr *SrcExpr, AssignmentAction Action, | |||
9804 | bool *Complained = nullptr); | |||
9805 | ||||
9806 | /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag | |||
9807 | /// enum. If AllowMask is true, then we also allow the complement of a valid | |||
9808 | /// value, to be used as a mask. | |||
9809 | bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | |||
9810 | bool AllowMask) const; | |||
9811 | ||||
9812 | /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant | |||
9813 | /// integer not in the range of enum values. | |||
9814 | void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, | |||
9815 | Expr *SrcExpr); | |||
9816 | ||||
9817 | /// CheckAssignmentConstraints - Perform type checking for assignment, | |||
9818 | /// argument passing, variable initialization, and function return values. | |||
9819 | /// C99 6.5.16. | |||
9820 | AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, | |||
9821 | QualType LHSType, | |||
9822 | QualType RHSType); | |||
9823 | ||||
9824 | /// Check assignment constraints and optionally prepare for a conversion of | |||
9825 | /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS | |||
9826 | /// is true. | |||
9827 | AssignConvertType CheckAssignmentConstraints(QualType LHSType, | |||
9828 | ExprResult &RHS, | |||
9829 | CastKind &Kind, | |||
9830 | bool ConvertRHS = true); | |||
9831 | ||||
9832 | /// Check assignment constraints for an assignment of RHS to LHSType. | |||
9833 | /// | |||
9834 | /// \param LHSType The destination type for the assignment. | |||
9835 | /// \param RHS The source expression for the assignment. | |||
9836 | /// \param Diagnose If \c true, diagnostics may be produced when checking | |||
9837 | /// for assignability. If a diagnostic is produced, \p RHS will be | |||
9838 | /// set to ExprError(). Note that this function may still return | |||
9839 | /// without producing a diagnostic, even for an invalid assignment. | |||
9840 | /// \param DiagnoseCFAudited If \c true, the target is a function parameter | |||
9841 | /// in an audited Core Foundation API and does not need to be checked | |||
9842 | /// for ARC retain issues. | |||
9843 | /// \param ConvertRHS If \c true, \p RHS will be updated to model the | |||
9844 | /// conversions necessary to perform the assignment. If \c false, | |||
9845 | /// \p Diagnose must also be \c false. | |||
9846 | AssignConvertType CheckSingleAssignmentConstraints( | |||
9847 | QualType LHSType, ExprResult &RHS, bool Diagnose = true, | |||
9848 | bool DiagnoseCFAudited = false, bool ConvertRHS = true); | |||
9849 | ||||
9850 | // If the lhs type is a transparent union, check whether we | |||
9851 | // can initialize the transparent union with the given expression. | |||
9852 | AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, | |||
9853 | ExprResult &RHS); | |||
9854 | ||||
9855 | bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); | |||
9856 | ||||
9857 | bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); | |||
9858 | ||||
9859 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, | |||
9860 | AssignmentAction Action, | |||
9861 | bool AllowExplicit = false); | |||
9862 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, | |||
9863 | AssignmentAction Action, | |||
9864 | bool AllowExplicit, | |||
9865 | ImplicitConversionSequence& ICS); | |||
9866 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, | |||
9867 | const ImplicitConversionSequence& ICS, | |||
9868 | AssignmentAction Action, | |||
9869 | CheckedConversionKind CCK | |||
9870 | = CCK_ImplicitConversion); | |||
9871 | ExprResult PerformImplicitConversion(Expr *From, QualType ToType, | |||
9872 | const StandardConversionSequence& SCS, | |||
9873 | AssignmentAction Action, | |||
9874 | CheckedConversionKind CCK); | |||
9875 | ||||
9876 | ExprResult PerformQualificationConversion( | |||
9877 | Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, | |||
9878 | CheckedConversionKind CCK = CCK_ImplicitConversion); | |||
9879 | ||||
9880 | /// the following "Check" methods will return a valid/converted QualType | |||
9881 | /// or a null QualType (indicating an error diagnostic was issued). | |||
9882 | ||||
9883 | /// type checking binary operators (subroutines of CreateBuiltinBinOp). | |||
9884 | QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, | |||
9885 | ExprResult &RHS); | |||
9886 | QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, | |||
9887 | ExprResult &RHS); | |||
9888 | QualType CheckPointerToMemberOperands( // C++ 5.5 | |||
9889 | ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, | |||
9890 | SourceLocation OpLoc, bool isIndirect); | |||
9891 | QualType CheckMultiplyDivideOperands( // C99 6.5.5 | |||
9892 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, | |||
9893 | bool IsDivide); | |||
9894 | QualType CheckRemainderOperands( // C99 6.5.5 | |||
9895 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, | |||
9896 | bool IsCompAssign = false); | |||
9897 | QualType CheckAdditionOperands( // C99 6.5.6 | |||
9898 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, | |||
9899 | BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); | |||
9900 | QualType CheckSubtractionOperands( // C99 6.5.6 | |||
9901 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, | |||
9902 | QualType* CompLHSTy = nullptr); | |||
9903 | QualType CheckShiftOperands( // C99 6.5.7 | |||
9904 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, | |||
9905 | BinaryOperatorKind Opc, bool IsCompAssign = false); | |||
9906 | QualType CheckCompareOperands( // C99 6.5.8/9 | |||
9907 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, | |||
9908 | BinaryOperatorKind Opc); | |||
9909 | QualType CheckBitwiseOperands( // C99 6.5.[10...12] | |||
9910 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, | |||
9911 | BinaryOperatorKind Opc); | |||
9912 | QualType CheckLogicalOperands( // C99 6.5.[13,14] | |||
9913 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, | |||
9914 | BinaryOperatorKind Opc); | |||
9915 | // CheckAssignmentOperands is used for both simple and compound assignment. | |||
9916 | // For simple assignment, pass both expressions and a null converted type. | |||
9917 | // For compound assignment, pass both expressions and the converted type. | |||
9918 | QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] | |||
9919 | Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); | |||
9920 | ||||
9921 | ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, | |||
9922 | UnaryOperatorKind Opcode, Expr *Op); | |||
9923 | ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, | |||
9924 | BinaryOperatorKind Opcode, | |||
9925 | Expr *LHS, Expr *RHS); | |||
9926 | ExprResult checkPseudoObjectRValue(Expr *E); | |||
9927 | Expr *recreateSyntacticForm(PseudoObjectExpr *E); | |||
9928 | ||||
9929 | QualType CheckConditionalOperands( // C99 6.5.15 | |||
9930 | ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, | |||
9931 | ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); | |||
9932 | QualType CXXCheckConditionalOperands( // C++ 5.16 | |||
9933 | ExprResult &cond, ExprResult &lhs, ExprResult &rhs, | |||
9934 | ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); | |||
9935 | QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, | |||
9936 | bool ConvertArgs = true); | |||
9937 | QualType FindCompositePointerType(SourceLocation Loc, | |||
9938 | ExprResult &E1, ExprResult &E2, | |||
9939 | bool ConvertArgs = true) { | |||
9940 | Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); | |||
9941 | QualType Composite = | |||
9942 | FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); | |||
9943 | E1 = E1Tmp; | |||
9944 | E2 = E2Tmp; | |||
9945 | return Composite; | |||
9946 | } | |||
9947 | ||||
9948 | QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, | |||
9949 | SourceLocation QuestionLoc); | |||
9950 | ||||
9951 | bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, | |||
9952 | SourceLocation QuestionLoc); | |||
9953 | ||||
9954 | void DiagnoseAlwaysNonNullPointer(Expr *E, | |||
9955 | Expr::NullPointerConstantKind NullType, | |||
9956 | bool IsEqual, SourceRange Range); | |||
9957 | ||||
9958 | /// type checking for vector binary operators. | |||
9959 | QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, | |||
9960 | SourceLocation Loc, bool IsCompAssign, | |||
9961 | bool AllowBothBool, bool AllowBoolConversion); | |||
9962 | QualType GetSignedVectorType(QualType V); | |||
9963 | QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, | |||
9964 | SourceLocation Loc, | |||
9965 | BinaryOperatorKind Opc); | |||
9966 | QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, | |||
9967 | SourceLocation Loc); | |||
9968 | ||||
9969 | bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); | |||
9970 | bool isLaxVectorConversion(QualType srcType, QualType destType); | |||
9971 | ||||
9972 | /// type checking declaration initializers (C99 6.7.8) | |||
9973 | bool CheckForConstantInitializer(Expr *e, QualType t); | |||
9974 | ||||
9975 | // type checking C++ declaration initializers (C++ [dcl.init]). | |||
9976 | ||||
9977 | /// ReferenceCompareResult - Expresses the result of comparing two | |||
9978 | /// types (cv1 T1 and cv2 T2) to determine their compatibility for the | |||
9979 | /// purposes of initialization by reference (C++ [dcl.init.ref]p4). | |||
9980 | enum ReferenceCompareResult { | |||
9981 | /// Ref_Incompatible - The two types are incompatible, so direct | |||
9982 | /// reference binding is not possible. | |||
9983 | Ref_Incompatible = 0, | |||
9984 | /// Ref_Related - The two types are reference-related, which means | |||
9985 | /// that their unqualified forms (T1 and T2) are either the same | |||
9986 | /// or T1 is a base class of T2. | |||
9987 | Ref_Related, | |||
9988 | /// Ref_Compatible - The two types are reference-compatible. | |||
9989 | Ref_Compatible | |||
9990 | }; | |||
9991 | ||||
9992 | ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, | |||
9993 | QualType T1, QualType T2, | |||
9994 | bool &DerivedToBase, | |||
9995 | bool &ObjCConversion, | |||
9996 | bool &ObjCLifetimeConversion); | |||
9997 | ||||
9998 | ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, | |||
9999 | Expr *CastExpr, CastKind &CastKind, | |||
10000 | ExprValueKind &VK, CXXCastPath &Path); | |||
10001 | ||||
10002 | /// Force an expression with unknown-type to an expression of the | |||
10003 | /// given type. | |||
10004 | ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); | |||
10005 | ||||
10006 | /// Type-check an expression that's being passed to an | |||
10007 | /// __unknown_anytype parameter. | |||
10008 | ExprResult checkUnknownAnyArg(SourceLocation callLoc, | |||
10009 | Expr *result, QualType ¶mType); | |||
10010 | ||||
10011 | // CheckVectorCast - check type constraints for vectors. | |||
10012 | // Since vectors are an extension, there are no C standard reference for this. | |||
10013 | // We allow casting between vectors and integer datatypes of the same size. | |||
10014 | // returns true if the cast is invalid | |||
10015 | bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, | |||
10016 | CastKind &Kind); | |||
10017 | ||||
10018 | /// Prepare `SplattedExpr` for a vector splat operation, adding | |||
10019 | /// implicit casts if necessary. | |||
10020 | ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); | |||
10021 | ||||
10022 | // CheckExtVectorCast - check type constraints for extended vectors. | |||
10023 | // Since vectors are an extension, there are no C standard reference for this. | |||
10024 | // We allow casting between vectors and integer datatypes of the same size, | |||
10025 | // or vectors and the element type of that vector. | |||
10026 | // returns the cast expr | |||
10027 | ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, | |||
10028 | CastKind &Kind); | |||
10029 | ||||
10030 | ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, | |||
10031 | SourceLocation LParenLoc, | |||
10032 | Expr *CastExpr, | |||
10033 | SourceLocation RParenLoc); | |||
10034 | ||||
10035 | enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; | |||
10036 | ||||
10037 | /// Checks for invalid conversions and casts between | |||
10038 | /// retainable pointers and other pointer kinds for ARC and Weak. | |||
10039 | ARCConversionResult CheckObjCConversion(SourceRange castRange, | |||
10040 | QualType castType, Expr *&op, | |||
10041 | CheckedConversionKind CCK, | |||
10042 | bool Diagnose = true, | |||
10043 | bool DiagnoseCFAudited = false, | |||
10044 | BinaryOperatorKind Opc = BO_PtrMemD | |||
10045 | ); | |||
10046 | ||||
10047 | Expr *stripARCUnbridgedCast(Expr *e); | |||
10048 | void diagnoseARCUnbridgedCast(Expr *e); | |||
10049 | ||||
10050 | bool CheckObjCARCUnavailableWeakConversion(QualType castType, | |||
10051 | QualType ExprType); | |||
10052 | ||||
10053 | /// checkRetainCycles - Check whether an Objective-C message send | |||
10054 | /// might create an obvious retain cycle. | |||
10055 | void checkRetainCycles(ObjCMessageExpr *msg); | |||
10056 | void checkRetainCycles(Expr *receiver, Expr *argument); | |||
10057 | void checkRetainCycles(VarDecl *Var, Expr *Init); | |||
10058 | ||||
10059 | /// checkUnsafeAssigns - Check whether +1 expr is being assigned | |||
10060 | /// to weak/__unsafe_unretained type. | |||
10061 | bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); | |||
10062 | ||||
10063 | /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned | |||
10064 | /// to weak/__unsafe_unretained expression. | |||
10065 | void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); | |||
10066 | ||||
10067 | /// CheckMessageArgumentTypes - Check types in an Obj-C message send. | |||
10068 | /// \param Method - May be null. | |||
10069 | /// \param [out] ReturnType - The return type of the send. | |||
10070 | /// \return true iff there were any incompatible types. | |||
10071 | bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, | |||
10072 | MultiExprArg Args, Selector Sel, | |||
10073 | ArrayRef<SourceLocation> SelectorLocs, | |||
10074 | ObjCMethodDecl *Method, bool isClassMessage, | |||
10075 | bool isSuperMessage, SourceLocation lbrac, | |||
10076 | SourceLocation rbrac, SourceRange RecRange, | |||
10077 | QualType &ReturnType, ExprValueKind &VK); | |||
10078 | ||||
10079 | /// Determine the result of a message send expression based on | |||
10080 | /// the type of the receiver, the method expected to receive the message, | |||
10081 | /// and the form of the message send. | |||
10082 | QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, | |||
10083 | ObjCMethodDecl *Method, bool isClassMessage, | |||
10084 | bool isSuperMessage); | |||
10085 | ||||
10086 | /// If the given expression involves a message send to a method | |||
10087 | /// with a related result type, emit a note describing what happened. | |||
10088 | void EmitRelatedResultTypeNote(const Expr *E); | |||
10089 | ||||
10090 | /// Given that we had incompatible pointer types in a return | |||
10091 | /// statement, check whether we're in a method with a related result | |||
10092 | /// type, and if so, emit a note describing what happened. | |||
10093 | void EmitRelatedResultTypeNoteForReturn(QualType destType); | |||
10094 | ||||
10095 | class ConditionResult { | |||
10096 | Decl *ConditionVar; | |||
10097 | FullExprArg Condition; | |||
10098 | bool Invalid; | |||
10099 | bool HasKnownValue; | |||
10100 | bool KnownValue; | |||
10101 | ||||
10102 | friend class Sema; | |||
10103 | ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, | |||
10104 | bool IsConstexpr) | |||
10105 | : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), | |||
10106 | HasKnownValue(IsConstexpr && Condition.get() && | |||
10107 | !Condition.get()->isValueDependent()), | |||
10108 | KnownValue(HasKnownValue && | |||
10109 | !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} | |||
10110 | explicit ConditionResult(bool Invalid) | |||
10111 | : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), | |||
10112 | HasKnownValue(false), KnownValue(false) {} | |||
10113 | ||||
10114 | public: | |||
10115 | ConditionResult() : ConditionResult(false) {} | |||
10116 | bool isInvalid() const { return Invalid; } | |||
10117 | std::pair<VarDecl *, Expr *> get() const { | |||
10118 | return std::make_pair(cast_or_null<VarDecl>(ConditionVar), | |||
10119 | Condition.get()); | |||
10120 | } | |||
10121 | llvm::Optional<bool> getKnownValue() const { | |||
10122 | if (!HasKnownValue) | |||
10123 | return None; | |||
10124 | return KnownValue; | |||
10125 | } | |||
10126 | }; | |||
10127 | static ConditionResult ConditionError() { return ConditionResult(true); } | |||
10128 | ||||
10129 | enum class ConditionKind { | |||
10130 | Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. | |||
10131 | ConstexprIf, ///< A constant boolean condition from 'if constexpr'. | |||
10132 | Switch ///< An integral condition for a 'switch' statement. | |||
10133 | }; | |||
10134 | ||||
10135 | ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, | |||
10136 | Expr *SubExpr, ConditionKind CK); | |||
10137 | ||||
10138 | ConditionResult ActOnConditionVariable(Decl *ConditionVar, | |||
10139 | SourceLocation StmtLoc, | |||
10140 | ConditionKind CK); | |||
10141 | ||||
10142 | DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); | |||
10143 | ||||
10144 | ExprResult CheckConditionVariable(VarDecl *ConditionVar, | |||
10145 | SourceLocation StmtLoc, | |||
10146 | ConditionKind CK); | |||
10147 | ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); | |||
10148 | ||||
10149 | /// CheckBooleanCondition - Diagnose problems involving the use of | |||
10150 | /// the given expression as a boolean condition (e.g. in an if | |||
10151 | /// statement). Also performs the standard function and array | |||
10152 | /// decays, possibly changing the input variable. | |||
10153 | /// | |||
10154 | /// \param Loc - A location associated with the condition, e.g. the | |||
10155 | /// 'if' keyword. | |||
10156 | /// \return true iff there were any errors | |||
10157 | ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, | |||
10158 | bool IsConstexpr = false); | |||
10159 | ||||
10160 | /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression | |||
10161 | /// found in an explicit(bool) specifier. | |||
10162 | ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); | |||
10163 | ||||
10164 | /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. | |||
10165 | /// Returns true if the explicit specifier is now resolved. | |||
10166 | bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); | |||
10167 | ||||
10168 | /// DiagnoseAssignmentAsCondition - Given that an expression is | |||
10169 | /// being used as a boolean condition, warn if it's an assignment. | |||
10170 | void DiagnoseAssignmentAsCondition(Expr *E); | |||
10171 | ||||
10172 | /// Redundant parentheses over an equality comparison can indicate | |||
10173 | /// that the user intended an assignment used as condition. | |||
10174 | void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); | |||
10175 | ||||
10176 | /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. | |||
10177 | ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); | |||
10178 | ||||
10179 | /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have | |||
10180 | /// the specified width and sign. If an overflow occurs, detect it and emit | |||
10181 | /// the specified diagnostic. | |||
10182 | void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, | |||
10183 | unsigned NewWidth, bool NewSign, | |||
10184 | SourceLocation Loc, unsigned DiagID); | |||
10185 | ||||
10186 | /// Checks that the Objective-C declaration is declared in the global scope. | |||
10187 | /// Emits an error and marks the declaration as invalid if it's not declared | |||
10188 | /// in the global scope. | |||
10189 | bool CheckObjCDeclScope(Decl *D); | |||
10190 | ||||
10191 | /// Abstract base class used for diagnosing integer constant | |||
10192 | /// expression violations. | |||
10193 | class VerifyICEDiagnoser { | |||
10194 | public: | |||
10195 | bool Suppress; | |||
10196 | ||||
10197 | VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } | |||
10198 | ||||
10199 | virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; | |||
10200 | virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); | |||
10201 | virtual ~VerifyICEDiagnoser() { } | |||
10202 | }; | |||
10203 | ||||
10204 | /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, | |||
10205 | /// and reports the appropriate diagnostics. Returns false on success. | |||
10206 | /// Can optionally return the value of the expression. | |||
10207 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | |||
10208 | VerifyICEDiagnoser &Diagnoser, | |||
10209 | bool AllowFold = true); | |||
10210 | ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, | |||
10211 | unsigned DiagID, | |||
10212 | bool AllowFold = true); | |||
10213 | ExprResult VerifyIntegerConstantExpression(Expr *E, | |||
10214 | llvm::APSInt *Result = nullptr); | |||
10215 | ||||
10216 | /// VerifyBitField - verifies that a bit field expression is an ICE and has | |||
10217 | /// the correct width, and that the field type is valid. | |||
10218 | /// Returns false on success. | |||
10219 | /// Can optionally return whether the bit-field is of width 0 | |||
10220 | ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, | |||
10221 | QualType FieldTy, bool IsMsStruct, | |||
10222 | Expr *BitWidth, bool *ZeroWidth = nullptr); | |||
10223 | ||||
10224 | private: | |||
10225 | unsigned ForceCUDAHostDeviceDepth = 0; | |||
10226 | ||||
10227 | public: | |||
10228 | /// Increments our count of the number of times we've seen a pragma forcing | |||
10229 | /// functions to be __host__ __device__. So long as this count is greater | |||
10230 | /// than zero, all functions encountered will be __host__ __device__. | |||
10231 | void PushForceCUDAHostDevice(); | |||
10232 | ||||
10233 | /// Decrements our count of the number of times we've seen a pragma forcing | |||
10234 | /// functions to be __host__ __device__. Returns false if the count is 0 | |||
10235 | /// before incrementing, so you can emit an error. | |||
10236 | bool PopForceCUDAHostDevice(); | |||
10237 | ||||
10238 | /// Diagnostics that are emitted only if we discover that the given function | |||
10239 | /// must be codegen'ed. Because handling these correctly adds overhead to | |||
10240 | /// compilation, this is currently only enabled for CUDA compilations. | |||
10241 | llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, | |||
10242 | std::vector<PartialDiagnosticAt>> | |||
10243 | DeviceDeferredDiags; | |||
10244 | ||||
10245 | /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the | |||
10246 | /// key in a hashtable, both the FD and location are hashed. | |||
10247 | struct FunctionDeclAndLoc { | |||
10248 | CanonicalDeclPtr<FunctionDecl> FD; | |||
10249 | SourceLocation Loc; | |||
10250 | }; | |||
10251 | ||||
10252 | /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a | |||
10253 | /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the | |||
10254 | /// same deferred diag twice. | |||
10255 | llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; | |||
10256 | ||||
10257 | /// An inverse call graph, mapping known-emitted functions to one of their | |||
10258 | /// known-emitted callers (plus the location of the call). | |||
10259 | /// | |||
10260 | /// Functions that we can tell a priori must be emitted aren't added to this | |||
10261 | /// map. | |||
10262 | llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, | |||
10263 | /* Caller = */ FunctionDeclAndLoc> | |||
10264 | DeviceKnownEmittedFns; | |||
10265 | ||||
10266 | /// A partial call graph maintained during CUDA/OpenMP device code compilation | |||
10267 | /// to support deferred diagnostics. | |||
10268 | /// | |||
10269 | /// Functions are only added here if, at the time they're considered, they are | |||
10270 | /// not known-emitted. As soon as we discover that a function is | |||
10271 | /// known-emitted, we remove it and everything it transitively calls from this | |||
10272 | /// set and add those functions to DeviceKnownEmittedFns. | |||
10273 | llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, | |||
10274 | /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, | |||
10275 | SourceLocation>> | |||
10276 | DeviceCallGraph; | |||
10277 | ||||
10278 | /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be | |||
10279 | /// deferred. | |||
10280 | /// | |||
10281 | /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) | |||
10282 | /// which are not allowed to appear inside __device__ functions and are | |||
10283 | /// allowed to appear in __host__ __device__ functions only if the host+device | |||
10284 | /// function is never codegen'ed. | |||
10285 | /// | |||
10286 | /// To handle this, we use the notion of "deferred diagnostics", where we | |||
10287 | /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. | |||
10288 | /// | |||
10289 | /// This class lets you emit either a regular diagnostic, a deferred | |||
10290 | /// diagnostic, or no diagnostic at all, according to an argument you pass to | |||
10291 | /// its constructor, thus simplifying the process of creating these "maybe | |||
10292 | /// deferred" diagnostics. | |||
10293 | class DeviceDiagBuilder { | |||
10294 | public: | |||
10295 | enum Kind { | |||
10296 | /// Emit no diagnostics. | |||
10297 | K_Nop, | |||
10298 | /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). | |||
10299 | K_Immediate, | |||
10300 | /// Emit the diagnostic immediately, and, if it's a warning or error, also | |||
10301 | /// emit a call stack showing how this function can be reached by an a | |||
10302 | /// priori known-emitted function. | |||
10303 | K_ImmediateWithCallStack, | |||
10304 | /// Create a deferred diagnostic, which is emitted only if the function | |||
10305 | /// it's attached to is codegen'ed. Also emit a call stack as with | |||
10306 | /// K_ImmediateWithCallStack. | |||
10307 | K_Deferred | |||
10308 | }; | |||
10309 | ||||
10310 | DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, | |||
10311 | FunctionDecl *Fn, Sema &S); | |||
10312 | DeviceDiagBuilder(DeviceDiagBuilder &&D); | |||
10313 | DeviceDiagBuilder(const DeviceDiagBuilder &) = default; | |||
10314 | ~DeviceDiagBuilder(); | |||
10315 | ||||
10316 | /// Convertible to bool: True if we immediately emitted an error, false if | |||
10317 | /// we didn't emit an error or we created a deferred error. | |||
10318 | /// | |||
10319 | /// Example usage: | |||
10320 | /// | |||
10321 | /// if (DeviceDiagBuilder(...) << foo << bar) | |||
10322 | /// return ExprError(); | |||
10323 | /// | |||
10324 | /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably | |||
10325 | /// want to use these instead of creating a DeviceDiagBuilder yourself. | |||
10326 | operator bool() const { return ImmediateDiag.hasValue(); } | |||
10327 | ||||
10328 | template <typename T> | |||
10329 | friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, | |||
10330 | const T &Value) { | |||
10331 | if (Diag.ImmediateDiag.hasValue()) | |||
10332 | *Diag.ImmediateDiag << Value; | |||
10333 | else if (Diag.PartialDiagId.hasValue()) | |||
10334 | Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second | |||
10335 | << Value; | |||
10336 | return Diag; | |||
10337 | } | |||
10338 | ||||
10339 | private: | |||
10340 | Sema &S; | |||
10341 | SourceLocation Loc; | |||
10342 | unsigned DiagID; | |||
10343 | FunctionDecl *Fn; | |||
10344 | bool ShowCallStack; | |||
10345 | ||||
10346 | // Invariant: At most one of these Optionals has a value. | |||
10347 | // FIXME: Switch these to a Variant once that exists. | |||
10348 | llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; | |||
10349 | llvm::Optional<unsigned> PartialDiagId; | |||
10350 | }; | |||
10351 | ||||
10352 | /// Indicate that this function (and thus everything it transtively calls) | |||
10353 | /// will be codegen'ed, and emit any deferred diagnostics on this function and | |||
10354 | /// its (transitive) callees. | |||
10355 | void markKnownEmitted( | |||
10356 | Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, | |||
10357 | SourceLocation OrigLoc, | |||
10358 | const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); | |||
10359 | ||||
10360 | /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context | |||
10361 | /// is "used as device code". | |||
10362 | /// | |||
10363 | /// - If CurContext is a __host__ function, does not emit any diagnostics. | |||
10364 | /// - If CurContext is a __device__ or __global__ function, emits the | |||
10365 | /// diagnostics immediately. | |||
10366 | /// - If CurContext is a __host__ __device__ function and we are compiling for | |||
10367 | /// the device, creates a diagnostic which is emitted if and when we realize | |||
10368 | /// that the function will be codegen'ed. | |||
10369 | /// | |||
10370 | /// Example usage: | |||
10371 | /// | |||
10372 | /// // Variable-length arrays are not allowed in CUDA device code. | |||
10373 | /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) | |||
10374 | /// return ExprError(); | |||
10375 | /// // Otherwise, continue parsing as normal. | |||
10376 | DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); | |||
10377 | ||||
10378 | /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context | |||
10379 | /// is "used as host code". | |||
10380 | /// | |||
10381 | /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. | |||
10382 | DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); | |||
10383 | ||||
10384 | /// Creates a DeviceDiagBuilder that emits the diagnostic if the current | |||
10385 | /// context is "used as device code". | |||
10386 | /// | |||
10387 | /// - If CurContext is a `declare target` function or it is known that the | |||
10388 | /// function is emitted for the device, emits the diagnostics immediately. | |||
10389 | /// - If CurContext is a non-`declare target` function and we are compiling | |||
10390 | /// for the device, creates a diagnostic which is emitted if and when we | |||
10391 | /// realize that the function will be codegen'ed. | |||
10392 | /// | |||
10393 | /// Example usage: | |||
10394 | /// | |||
10395 | /// // Variable-length arrays are not allowed in NVPTX device code. | |||
10396 | /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) | |||
10397 | /// return ExprError(); | |||
10398 | /// // Otherwise, continue parsing as normal. | |||
10399 | DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); | |||
10400 | ||||
10401 | DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); | |||
10402 | ||||
10403 | enum CUDAFunctionTarget { | |||
10404 | CFT_Device, | |||
10405 | CFT_Global, | |||
10406 | CFT_Host, | |||
10407 | CFT_HostDevice, | |||
10408 | CFT_InvalidTarget | |||
10409 | }; | |||
10410 | ||||
10411 | /// Determines whether the given function is a CUDA device/host/kernel/etc. | |||
10412 | /// function. | |||
10413 | /// | |||
10414 | /// Use this rather than examining the function's attributes yourself -- you | |||
10415 | /// will get it wrong. Returns CFT_Host if D is null. | |||
10416 | CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, | |||
10417 | bool IgnoreImplicitHDAttr = false); | |||
10418 | CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); | |||
10419 | ||||
10420 | /// Gets the CUDA target for the current context. | |||
10421 | CUDAFunctionTarget CurrentCUDATarget() { | |||
10422 | return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); | |||
10423 | } | |||
10424 | ||||
10425 | // CUDA function call preference. Must be ordered numerically from | |||
10426 | // worst to best. | |||
10427 | enum CUDAFunctionPreference { | |||
10428 | CFP_Never, // Invalid caller/callee combination. | |||
10429 | CFP_WrongSide, // Calls from host-device to host or device | |||
10430 | // function that do not match current compilation | |||
10431 | // mode. | |||
10432 | CFP_HostDevice, // Any calls to host/device functions. | |||
10433 | CFP_SameSide, // Calls from host-device to host or device | |||
10434 | // function matching current compilation mode. | |||
10435 | CFP_Native, // host-to-host or device-to-device calls. | |||
10436 | }; | |||
10437 | ||||
10438 | /// Identifies relative preference of a given Caller/Callee | |||
10439 | /// combination, based on their host/device attributes. | |||
10440 | /// \param Caller function which needs address of \p Callee. | |||
10441 | /// nullptr in case of global context. | |||
10442 | /// \param Callee target function | |||
10443 | /// | |||
10444 | /// \returns preference value for particular Caller/Callee combination. | |||
10445 | CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, | |||
10446 | const FunctionDecl *Callee); | |||
10447 | ||||
10448 | /// Determines whether Caller may invoke Callee, based on their CUDA | |||
10449 | /// host/device attributes. Returns false if the call is not allowed. | |||
10450 | /// | |||
10451 | /// Note: Will return true for CFP_WrongSide calls. These may appear in | |||
10452 | /// semantically correct CUDA programs, but only if they're never codegen'ed. | |||
10453 | bool IsAllowedCUDACall(const FunctionDecl *Caller, | |||
10454 | const FunctionDecl *Callee) { | |||
10455 | return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; | |||
10456 | } | |||
10457 | ||||
10458 | /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, | |||
10459 | /// depending on FD and the current compilation settings. | |||
10460 | void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, | |||
10461 | const LookupResult &Previous); | |||
10462 | ||||
10463 | public: | |||
10464 | /// Check whether we're allowed to call Callee from the current context. | |||
10465 | /// | |||
10466 | /// - If the call is never allowed in a semantically-correct program | |||
10467 | /// (CFP_Never), emits an error and returns false. | |||
10468 | /// | |||
10469 | /// - If the call is allowed in semantically-correct programs, but only if | |||
10470 | /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to | |||
10471 | /// be emitted if and when the caller is codegen'ed, and returns true. | |||
10472 | /// | |||
10473 | /// Will only create deferred diagnostics for a given SourceLocation once, | |||
10474 | /// so you can safely call this multiple times without generating duplicate | |||
10475 | /// deferred errors. | |||
10476 | /// | |||
10477 | /// - Otherwise, returns true without emitting any diagnostics. | |||
10478 | bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); | |||
10479 | ||||
10480 | /// Set __device__ or __host__ __device__ attributes on the given lambda | |||
10481 | /// operator() method. | |||
10482 | /// | |||
10483 | /// CUDA lambdas declared inside __device__ or __global__ functions inherit | |||
10484 | /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ | |||
10485 | /// functions become __host__ __device__ themselves. | |||
10486 | void CUDASetLambdaAttrs(CXXMethodDecl *Method); | |||
10487 | ||||
10488 | /// Finds a function in \p Matches with highest calling priority | |||
10489 | /// from \p Caller context and erases all functions with lower | |||
10490 | /// calling priority. | |||
10491 | void EraseUnwantedCUDAMatches( | |||
10492 | const FunctionDecl *Caller, | |||
10493 | SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); | |||
10494 | ||||
10495 | /// Given a implicit special member, infer its CUDA target from the | |||
10496 | /// calls it needs to make to underlying base/field special members. | |||
10497 | /// \param ClassDecl the class for which the member is being created. | |||
10498 | /// \param CSM the kind of special member. | |||
10499 | /// \param MemberDecl the special member itself. | |||
10500 | /// \param ConstRHS true if this is a copy operation with a const object on | |||
10501 | /// its RHS. | |||
10502 | /// \param Diagnose true if this call should emit diagnostics. | |||
10503 | /// \return true if there was an error inferring. | |||
10504 | /// The result of this call is implicit CUDA target attribute(s) attached to | |||
10505 | /// the member declaration. | |||
10506 | bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, | |||
10507 | CXXSpecialMember CSM, | |||
10508 | CXXMethodDecl *MemberDecl, | |||
10509 | bool ConstRHS, | |||
10510 | bool Diagnose); | |||
10511 | ||||
10512 | /// \return true if \p CD can be considered empty according to CUDA | |||
10513 | /// (E.2.3.1 in CUDA 7.5 Programming guide). | |||
10514 | bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); | |||
10515 | bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); | |||
10516 | ||||
10517 | // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In | |||
10518 | // case of error emits appropriate diagnostic and invalidates \p Var. | |||
10519 | // | |||
10520 | // \details CUDA allows only empty constructors as initializers for global | |||
10521 | // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all | |||
10522 | // __shared__ variables whether they are local or not (they all are implicitly | |||
10523 | // static in CUDA). One exception is that CUDA allows constant initializers | |||
10524 | // for __constant__ and __device__ variables. | |||
10525 | void checkAllowedCUDAInitializer(VarDecl *VD); | |||
10526 | ||||
10527 | /// Check whether NewFD is a valid overload for CUDA. Emits | |||
10528 | /// diagnostics and invalidates NewFD if not. | |||
10529 | void checkCUDATargetOverload(FunctionDecl *NewFD, | |||
10530 | const LookupResult &Previous); | |||
10531 | /// Copies target attributes from the template TD to the function FD. | |||
10532 | void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); | |||
10533 | ||||
10534 | /// Returns the name of the launch configuration function. This is the name | |||
10535 | /// of the function that will be called to configure kernel call, with the | |||
10536 | /// parameters specified via <<<>>>. | |||
10537 | std::string getCudaConfigureFuncName() const; | |||
10538 | ||||
10539 | /// \name Code completion | |||
10540 | //@{ | |||
10541 | /// Describes the context in which code completion occurs. | |||
10542 | enum ParserCompletionContext { | |||
10543 | /// Code completion occurs at top-level or namespace context. | |||
10544 | PCC_Namespace, | |||
10545 | /// Code completion occurs within a class, struct, or union. | |||
10546 | PCC_Class, | |||
10547 | /// Code completion occurs within an Objective-C interface, protocol, | |||
10548 | /// or category. | |||
10549 | PCC_ObjCInterface, | |||
10550 | /// Code completion occurs within an Objective-C implementation or | |||
10551 | /// category implementation | |||
10552 | PCC_ObjCImplementation, | |||
10553 | /// Code completion occurs within the list of instance variables | |||
10554 | /// in an Objective-C interface, protocol, category, or implementation. | |||
10555 | PCC_ObjCInstanceVariableList, | |||
10556 | /// Code completion occurs following one or more template | |||
10557 | /// headers. | |||
10558 | PCC_Template, | |||
10559 | /// Code completion occurs following one or more template | |||
10560 | /// headers within a class. | |||
10561 | PCC_MemberTemplate, | |||
10562 | /// Code completion occurs within an expression. | |||
10563 | PCC_Expression, | |||
10564 | /// Code completion occurs within a statement, which may | |||
10565 | /// also be an expression or a declaration. | |||
10566 | PCC_Statement, | |||
10567 | /// Code completion occurs at the beginning of the | |||
10568 | /// initialization statement (or expression) in a for loop. | |||
10569 | PCC_ForInit, | |||
10570 | /// Code completion occurs within the condition of an if, | |||
10571 | /// while, switch, or for statement. | |||
10572 | PCC_Condition, | |||
10573 | /// Code completion occurs within the body of a function on a | |||
10574 | /// recovery path, where we do not have a specific handle on our position | |||
10575 | /// in the grammar. | |||
10576 | PCC_RecoveryInFunction, | |||
10577 | /// Code completion occurs where only a type is permitted. | |||
10578 | PCC_Type, | |||
10579 | /// Code completion occurs in a parenthesized expression, which | |||
10580 | /// might also be a type cast. | |||
10581 | PCC_ParenthesizedExpression, | |||
10582 | /// Code completion occurs within a sequence of declaration | |||
10583 | /// specifiers within a function, method, or block. | |||
10584 | PCC_LocalDeclarationSpecifiers | |||
10585 | }; | |||
10586 | ||||
10587 | void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); | |||
10588 | void CodeCompleteOrdinaryName(Scope *S, | |||
10589 | ParserCompletionContext CompletionContext); | |||
10590 | void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, | |||
10591 | bool AllowNonIdentifiers, | |||
10592 | bool AllowNestedNameSpecifiers); | |||
10593 | ||||
10594 | struct CodeCompleteExpressionData; | |||
10595 | void CodeCompleteExpression(Scope *S, | |||
10596 | const CodeCompleteExpressionData &Data); | |||
10597 | void CodeCompleteExpression(Scope *S, QualType PreferredType, | |||
10598 | bool IsParenthesized = false); | |||
10599 | void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, | |||
10600 | SourceLocation OpLoc, bool IsArrow, | |||
10601 | bool IsBaseExprStatement, | |||
10602 | QualType PreferredType); | |||
10603 | void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, | |||
10604 | QualType PreferredType); | |||
10605 | void CodeCompleteTag(Scope *S, unsigned TagSpec); | |||
10606 | void CodeCompleteTypeQualifiers(DeclSpec &DS); | |||
10607 | void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, | |||
10608 | const VirtSpecifiers *VS = nullptr); | |||
10609 | void CodeCompleteBracketDeclarator(Scope *S); | |||
10610 | void CodeCompleteCase(Scope *S); | |||
10611 | /// Reports signatures for a call to CodeCompleteConsumer and returns the | |||
10612 | /// preferred type for the current argument. Returned type can be null. | |||
10613 | QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, | |||
10614 | SourceLocation OpenParLoc); | |||
10615 | QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, | |||
10616 | SourceLocation Loc, | |||
10617 | ArrayRef<Expr *> Args, | |||
10618 | SourceLocation OpenParLoc); | |||
10619 | QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, | |||
10620 | CXXScopeSpec SS, | |||
10621 | ParsedType TemplateTypeTy, | |||
10622 | ArrayRef<Expr *> ArgExprs, | |||
10623 | IdentifierInfo *II, | |||
10624 | SourceLocation OpenParLoc); | |||
10625 | void CodeCompleteInitializer(Scope *S, Decl *D); | |||
10626 | void CodeCompleteAfterIf(Scope *S); | |||
10627 | ||||
10628 | void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, | |||
10629 | bool EnteringContext, QualType BaseType); | |||
10630 | void CodeCompleteUsing(Scope *S); | |||
10631 | void CodeCompleteUsingDirective(Scope *S); | |||
10632 | void CodeCompleteNamespaceDecl(Scope *S); | |||
10633 | void CodeCompleteNamespaceAliasDecl(Scope *S); | |||
10634 | void CodeCompleteOperatorName(Scope *S); | |||
10635 | void CodeCompleteConstructorInitializer( | |||
10636 | Decl *Constructor, | |||
10637 | ArrayRef<CXXCtorInitializer *> Initializers); | |||
10638 | ||||
10639 | void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, | |||
10640 | bool AfterAmpersand); | |||
10641 | ||||
10642 | void CodeCompleteObjCAtDirective(Scope *S); | |||
10643 | void CodeCompleteObjCAtVisibility(Scope *S); | |||
10644 | void CodeCompleteObjCAtStatement(Scope *S); | |||
10645 | void CodeCompleteObjCAtExpression(Scope *S); | |||
10646 | void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); | |||
10647 | void CodeCompleteObjCPropertyGetter(Scope *S); | |||
10648 | void CodeCompleteObjCPropertySetter(Scope *S); | |||
10649 | void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, | |||
10650 | bool IsParameter); | |||
10651 | void CodeCompleteObjCMessageReceiver(Scope *S); | |||
10652 | void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, | |||
10653 | ArrayRef<IdentifierInfo *> SelIdents, | |||
10654 | bool AtArgumentExpression); | |||
10655 | void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, | |||
10656 | ArrayRef<IdentifierInfo *> SelIdents, | |||
10657 | bool AtArgumentExpression, | |||
10658 | bool IsSuper = false); | |||
10659 | void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, | |||
10660 | ArrayRef<IdentifierInfo *> SelIdents, | |||
10661 | bool AtArgumentExpression, | |||
10662 | ObjCInterfaceDecl *Super = nullptr); | |||
10663 | void CodeCompleteObjCForCollection(Scope *S, | |||
10664 | DeclGroupPtrTy IterationVar); | |||
10665 | void CodeCompleteObjCSelector(Scope *S, | |||
10666 | ArrayRef<IdentifierInfo *> SelIdents); | |||
10667 | void CodeCompleteObjCProtocolReferences( | |||
10668 | ArrayRef<IdentifierLocPair> Protocols); | |||
10669 | void CodeCompleteObjCProtocolDecl(Scope *S); | |||
10670 | void CodeCompleteObjCInterfaceDecl(Scope *S); | |||
10671 | void CodeCompleteObjCSuperclass(Scope *S, | |||
10672 | IdentifierInfo *ClassName, | |||
10673 | SourceLocation ClassNameLoc); | |||
10674 | void CodeCompleteObjCImplementationDecl(Scope *S); | |||
10675 | void CodeCompleteObjCInterfaceCategory(Scope *S, | |||
10676 | IdentifierInfo *ClassName, | |||
10677 | SourceLocation ClassNameLoc); | |||
10678 | void CodeCompleteObjCImplementationCategory(Scope *S, | |||
10679 | IdentifierInfo *ClassName, | |||
10680 | SourceLocation ClassNameLoc); | |||
10681 | void CodeCompleteObjCPropertyDefinition(Scope *S); | |||
10682 | void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, | |||
10683 | IdentifierInfo *PropertyName); | |||
10684 | void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, | |||
10685 | ParsedType ReturnType); | |||
10686 | void CodeCompleteObjCMethodDeclSelector(Scope *S, | |||
10687 | bool IsInstanceMethod, | |||
10688 | bool AtParameterName, | |||
10689 | ParsedType ReturnType, | |||
10690 | ArrayRef<IdentifierInfo *> SelIdents); | |||
10691 | void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, | |||
10692 | SourceLocation ClassNameLoc, | |||
10693 | bool IsBaseExprStatement); | |||
10694 | void CodeCompletePreprocessorDirective(bool InConditional); | |||
10695 | void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); | |||
10696 | void CodeCompletePreprocessorMacroName(bool IsDefinition); | |||
10697 | void CodeCompletePreprocessorExpression(); | |||
10698 | void CodeCompletePreprocessorMacroArgument(Scope *S, | |||
10699 | IdentifierInfo *Macro, | |||
10700 | MacroInfo *MacroInfo, | |||
10701 | unsigned Argument); | |||
10702 | void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); | |||
10703 | void CodeCompleteNaturalLanguage(); | |||
10704 | void CodeCompleteAvailabilityPlatformName(); | |||
10705 | void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, | |||
10706 | CodeCompletionTUInfo &CCTUInfo, | |||
10707 | SmallVectorImpl<CodeCompletionResult> &Results); | |||
10708 | //@} | |||
10709 | ||||
10710 | //===--------------------------------------------------------------------===// | |||
10711 | // Extra semantic analysis beyond the C type system | |||
10712 | ||||
10713 | public: | |||
10714 | SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, | |||
10715 | unsigned ByteNo) const; | |||
10716 | ||||
10717 | private: | |||
10718 | void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, | |||
10719 | const ArraySubscriptExpr *ASE=nullptr, | |||
10720 | bool AllowOnePastEnd=true, bool IndexNegated=false); | |||
10721 | void CheckArrayAccess(const Expr *E); | |||
10722 | // Used to grab the relevant information from a FormatAttr and a | |||
10723 | // FunctionDeclaration. | |||
10724 | struct FormatStringInfo { | |||
10725 | unsigned FormatIdx; | |||
10726 | unsigned FirstDataArg; | |||
10727 | bool HasVAListArg; | |||
10728 | }; | |||
10729 | ||||
10730 | static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, | |||
10731 | FormatStringInfo *FSI); | |||
10732 | bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, | |||
10733 | const FunctionProtoType *Proto); | |||
10734 | bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, | |||
10735 | ArrayRef<const Expr *> Args); | |||
10736 | bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, | |||
10737 | const FunctionProtoType *Proto); | |||
10738 | bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); | |||
10739 | void CheckConstructorCall(FunctionDecl *FDecl, | |||
10740 | ArrayRef<const Expr *> Args, | |||
10741 | const FunctionProtoType *Proto, | |||
10742 | SourceLocation Loc); | |||
10743 | ||||
10744 | void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, | |||
10745 | const Expr *ThisArg, ArrayRef<const Expr *> Args, | |||
10746 | bool IsMemberFunction, SourceLocation Loc, SourceRange Range, | |||
10747 | VariadicCallType CallType); | |||
10748 | ||||
10749 | bool CheckObjCString(Expr *Arg); | |||
10750 | ExprResult CheckOSLogFormatStringArg(Expr *Arg); | |||
10751 | ||||
10752 | ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, | |||
10753 | unsigned BuiltinID, CallExpr *TheCall); | |||
10754 | void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); | |||
10755 | ||||
10756 | bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, | |||
10757 | unsigned MaxWidth); | |||
10758 | bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10759 | bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10760 | ||||
10761 | bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10762 | bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10763 | bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); | |||
10764 | bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); | |||
10765 | bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10766 | bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10767 | bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); | |||
10768 | bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); | |||
10769 | bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10770 | bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10771 | ||||
10772 | bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); | |||
10773 | bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); | |||
10774 | bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); | |||
10775 | bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); | |||
10776 | bool SemaBuiltinVSX(CallExpr *TheCall); | |||
10777 | bool SemaBuiltinOSLogFormat(CallExpr *TheCall); | |||
10778 | ||||
10779 | public: | |||
10780 | // Used by C++ template instantiation. | |||
10781 | ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); | |||
10782 | ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, | |||
10783 | SourceLocation BuiltinLoc, | |||
10784 | SourceLocation RParenLoc); | |||
10785 | ||||
10786 | private: | |||
10787 | bool SemaBuiltinPrefetch(CallExpr *TheCall); | |||
10788 | bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); | |||
10789 | bool SemaBuiltinAssume(CallExpr *TheCall); | |||
10790 | bool SemaBuiltinAssumeAligned(CallExpr *TheCall); | |||
10791 | bool SemaBuiltinLongjmp(CallExpr *TheCall); | |||
10792 | bool SemaBuiltinSetjmp(CallExpr *TheCall); | |||
10793 | ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); | |||
10794 | ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); | |||
10795 | ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, | |||
10796 | AtomicExpr::AtomicOp Op); | |||
10797 | ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, | |||
10798 | bool IsDelete); | |||
10799 | bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, | |||
10800 | llvm::APSInt &Result); | |||
10801 | bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, | |||
10802 | int High, bool RangeIsError = true); | |||
10803 | bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, | |||
10804 | unsigned Multiple); | |||
10805 | bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, | |||
10806 | int ArgNum, unsigned ExpectedFieldNum, | |||
10807 | bool AllowName); | |||
10808 | bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); | |||
10809 | public: | |||
10810 | enum FormatStringType { | |||
10811 | FST_Scanf, | |||
10812 | FST_Printf, | |||
10813 | FST_NSString, | |||
10814 | FST_Strftime, | |||
10815 | FST_Strfmon, | |||
10816 | FST_Kprintf, | |||
10817 | FST_FreeBSDKPrintf, | |||
10818 | FST_OSTrace, | |||
10819 | FST_OSLog, | |||
10820 | FST_Unknown | |||
10821 | }; | |||
10822 | static FormatStringType GetFormatStringType(const FormatAttr *Format); | |||
10823 | ||||
10824 | bool FormatStringHasSArg(const StringLiteral *FExpr); | |||
10825 | ||||
10826 | static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); | |||
10827 | ||||
10828 | private: | |||
10829 | bool CheckFormatArguments(const FormatAttr *Format, | |||
10830 | ArrayRef<const Expr *> Args, | |||
10831 | bool IsCXXMember, | |||
10832 | VariadicCallType CallType, | |||
10833 | SourceLocation Loc, SourceRange Range, | |||
10834 | llvm::SmallBitVector &CheckedVarArgs); | |||
10835 | bool CheckFormatArguments(ArrayRef<const Expr *> Args, | |||
10836 | bool HasVAListArg, unsigned format_idx, | |||
10837 | unsigned firstDataArg, FormatStringType Type, | |||
10838 | VariadicCallType CallType, | |||
10839 | SourceLocation Loc, SourceRange range, | |||
10840 | llvm::SmallBitVector &CheckedVarArgs); | |||
10841 | ||||
10842 | void CheckAbsoluteValueFunction(const CallExpr *Call, | |||
10843 | const FunctionDecl *FDecl); | |||
10844 | ||||
10845 | void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); | |||
10846 | ||||
10847 | void CheckMemaccessArguments(const CallExpr *Call, | |||
10848 | unsigned BId, | |||
10849 | IdentifierInfo *FnName); | |||
10850 | ||||
10851 | void CheckStrlcpycatArguments(const CallExpr *Call, | |||
10852 | IdentifierInfo *FnName); | |||
10853 | ||||
10854 | void CheckStrncatArguments(const CallExpr *Call, | |||
10855 | IdentifierInfo *FnName); | |||
10856 | ||||
10857 | void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, | |||
10858 | SourceLocation ReturnLoc, | |||
10859 | bool isObjCMethod = false, | |||
10860 | const AttrVec *Attrs = nullptr, | |||
10861 | const FunctionDecl *FD = nullptr); | |||
10862 | ||||
10863 | public: | |||
10864 | void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); | |||
10865 | ||||
10866 | private: | |||
10867 | void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); | |||
10868 | void CheckBoolLikeConversion(Expr *E, SourceLocation CC); | |||
10869 | void CheckForIntOverflow(Expr *E); | |||
10870 | void CheckUnsequencedOperations(Expr *E); | |||
10871 | ||||
10872 | /// Perform semantic checks on a completed expression. This will either | |||
10873 | /// be a full-expression or a default argument expression. | |||
10874 | void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), | |||
10875 | bool IsConstexpr = false); | |||
10876 | ||||
10877 | void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, | |||
10878 | Expr *Init); | |||
10879 | ||||
10880 | /// Check if there is a field shadowing. | |||
10881 | void CheckShadowInheritedFields(const SourceLocation &Loc, | |||
10882 | DeclarationName FieldName, | |||
10883 | const CXXRecordDecl *RD, | |||
10884 | bool DeclIsField = true); | |||
10885 | ||||
10886 | /// Check if the given expression contains 'break' or 'continue' | |||
10887 | /// statement that produces control flow different from GCC. | |||
10888 | void CheckBreakContinueBinding(Expr *E); | |||
10889 | ||||
10890 | /// Check whether receiver is mutable ObjC container which | |||
10891 | /// attempts to add itself into the container | |||
10892 | void CheckObjCCircularContainer(ObjCMessageExpr *Message); | |||
10893 | ||||
10894 | void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); | |||
10895 | void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, | |||
10896 | bool DeleteWasArrayForm); | |||
10897 | public: | |||
10898 | /// Register a magic integral constant to be used as a type tag. | |||
10899 | void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, | |||
10900 | uint64_t MagicValue, QualType Type, | |||
10901 | bool LayoutCompatible, bool MustBeNull); | |||
10902 | ||||
10903 | struct TypeTagData { | |||
10904 | TypeTagData() {} | |||
10905 | ||||
10906 | TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : | |||
10907 | Type(Type), LayoutCompatible(LayoutCompatible), | |||
10908 | MustBeNull(MustBeNull) | |||
10909 | {} | |||
10910 | ||||
10911 | QualType Type; | |||
10912 | ||||
10913 | /// If true, \c Type should be compared with other expression's types for | |||
10914 | /// layout-compatibility. | |||
10915 | unsigned LayoutCompatible : 1; | |||
10916 | unsigned MustBeNull : 1; | |||
10917 | }; | |||
10918 | ||||
10919 | /// A pair of ArgumentKind identifier and magic value. This uniquely | |||
10920 | /// identifies the magic value. | |||
10921 | typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; | |||
10922 | ||||
10923 | private: | |||
10924 | /// A map from magic value to type information. | |||
10925 | std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> | |||
10926 | TypeTagForDatatypeMagicValues; | |||
10927 | ||||
10928 | /// Peform checks on a call of a function with argument_with_type_tag | |||
10929 | /// or pointer_with_type_tag attributes. | |||
10930 | void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, | |||
10931 | const ArrayRef<const Expr *> ExprArgs, | |||
10932 | SourceLocation CallSiteLoc); | |||
10933 | ||||
10934 | /// Check if we are taking the address of a packed field | |||
10935 | /// as this may be a problem if the pointer value is dereferenced. | |||
10936 | void CheckAddressOfPackedMember(Expr *rhs); | |||
10937 | ||||
10938 | /// The parser's current scope. | |||
10939 | /// | |||
10940 | /// The parser maintains this state here. | |||
10941 | Scope *CurScope; | |||
10942 | ||||
10943 | mutable IdentifierInfo *Ident_super; | |||
10944 | mutable IdentifierInfo *Ident___float128; | |||
10945 | ||||
10946 | /// Nullability type specifiers. | |||
10947 | IdentifierInfo *Ident__Nonnull = nullptr; | |||
10948 | IdentifierInfo *Ident__Nullable = nullptr; | |||
10949 | IdentifierInfo *Ident__Null_unspecified = nullptr; | |||
10950 | ||||
10951 | IdentifierInfo *Ident_NSError = nullptr; | |||
10952 | ||||
10953 | /// The handler for the FileChanged preprocessor events. | |||
10954 | /// | |||
10955 | /// Used for diagnostics that implement custom semantic analysis for #include | |||
10956 | /// directives, like -Wpragma-pack. | |||
10957 | sema::SemaPPCallbacks *SemaPPCallbackHandler; | |||
10958 | ||||
10959 | protected: | |||
10960 | friend class Parser; | |||
10961 | friend class InitializationSequence; | |||
10962 | friend class ASTReader; | |||
10963 | friend class ASTDeclReader; | |||
10964 | friend class ASTWriter; | |||
10965 | ||||
10966 | public: | |||
10967 | /// Retrieve the keyword associated | |||
10968 | IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); | |||
10969 | ||||
10970 | /// The struct behind the CFErrorRef pointer. | |||
10971 | RecordDecl *CFError = nullptr; | |||
10972 | ||||
10973 | /// Retrieve the identifier "NSError". | |||
10974 | IdentifierInfo *getNSErrorIdent(); | |||
10975 | ||||
10976 | /// Retrieve the parser's current scope. | |||
10977 | /// | |||
10978 | /// This routine must only be used when it is certain that semantic analysis | |||
10979 | /// and the parser are in precisely the same context, which is not the case | |||
10980 | /// when, e.g., we are performing any kind of template instantiation. | |||
10981 | /// Therefore, the only safe places to use this scope are in the parser | |||
10982 | /// itself and in routines directly invoked from the parser and *never* from | |||
10983 | /// template substitution or instantiation. | |||
10984 | Scope *getCurScope() const { return CurScope; } | |||
10985 | ||||
10986 | void incrementMSManglingNumber() const { | |||
10987 | return CurScope->incrementMSManglingNumber(); | |||
10988 | } | |||
10989 | ||||
10990 | IdentifierInfo *getSuperIdentifier() const; | |||
10991 | IdentifierInfo *getFloat128Identifier() const; | |||
10992 | ||||
10993 | Decl *getObjCDeclContext() const; | |||
10994 | ||||
10995 | DeclContext *getCurLexicalContext() const { | |||
10996 | return OriginalLexicalContext ? OriginalLexicalContext : CurContext; | |||
10997 | } | |||
10998 | ||||
10999 | const DeclContext *getCurObjCLexicalContext() const { | |||
11000 | const DeclContext *DC = getCurLexicalContext(); | |||
11001 | // A category implicitly has the attribute of the interface. | |||
11002 | if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) | |||
11003 | DC = CatD->getClassInterface(); | |||
11004 | return DC; | |||
11005 | } | |||
11006 | ||||
11007 | /// To be used for checking whether the arguments being passed to | |||
11008 | /// function exceeds the number of parameters expected for it. | |||
11009 | static bool TooManyArguments(size_t NumParams, size_t NumArgs, | |||
11010 | bool PartialOverloading = false) { | |||
11011 | // We check whether we're just after a comma in code-completion. | |||
11012 | if (NumArgs > 0 && PartialOverloading) | |||
11013 | return NumArgs + 1 > NumParams; // If so, we view as an extra argument. | |||
11014 | return NumArgs > NumParams; | |||
11015 | } | |||
11016 | ||||
11017 | // Emitting members of dllexported classes is delayed until the class | |||
11018 | // (including field initializers) is fully parsed. | |||
11019 | SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; | |||
11020 | ||||
11021 | private: | |||
11022 | class SavePendingParsedClassStateRAII { | |||
11023 | public: | |||
11024 | SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } | |||
11025 | ||||
11026 | ~SavePendingParsedClassStateRAII() { | |||
11027 | assert(S.DelayedOverridingExceptionSpecChecks.empty() &&((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 11028, __PRETTY_FUNCTION__)) | |||
11028 | "there shouldn't be any pending delayed exception spec checks")((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 11028, __PRETTY_FUNCTION__)); | |||
11029 | assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 11030, __PRETTY_FUNCTION__)) | |||
11030 | "there shouldn't be any pending delayed exception spec checks")((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 11030, __PRETTY_FUNCTION__)); | |||
11031 | assert(S.DelayedDllExportClasses.empty() &&((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 11032, __PRETTY_FUNCTION__)) | |||
11032 | "there shouldn't be any pending delayed DLL export classes")((S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes" ) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\"" , "/build/llvm-toolchain-snapshot-9~svn360410/tools/clang/include/clang/Sema/Sema.h" , 11032, __PRETTY_FUNCTION__)); | |||
11033 | swapSavedState(); | |||
11034 | } | |||
11035 | ||||
11036 | private: | |||
11037 | Sema &S; | |||
11038 | decltype(DelayedOverridingExceptionSpecChecks) | |||
11039 | SavedOverridingExceptionSpecChecks; | |||
11040 | decltype(DelayedEquivalentExceptionSpecChecks) | |||
11041 | SavedEquivalentExceptionSpecChecks; | |||
11042 | decltype(DelayedDllExportClasses) SavedDllExportClasses; | |||
11043 | ||||
11044 | void swapSavedState() { | |||
11045 | SavedOverridingExceptionSpecChecks.swap( | |||
11046 | S.DelayedOverridingExceptionSpecChecks); | |||
11047 | SavedEquivalentExceptionSpecChecks.swap( | |||
11048 | S.DelayedEquivalentExceptionSpecChecks); | |||
11049 | SavedDllExportClasses.swap(S.DelayedDllExportClasses); | |||
11050 | } | |||
11051 | }; | |||
11052 | ||||
11053 | /// Helper class that collects misaligned member designations and | |||
11054 | /// their location info for delayed diagnostics. | |||
11055 | struct MisalignedMember { | |||
11056 | Expr *E; | |||
11057 | RecordDecl *RD; | |||
11058 | ValueDecl *MD; | |||
11059 | CharUnits Alignment; | |||
11060 | ||||
11061 | MisalignedMember() : E(), RD(), MD(), Alignment() {} | |||
11062 | MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, | |||
11063 | CharUnits Alignment) | |||
11064 | : E(E), RD(RD), MD(MD), Alignment(Alignment) {} | |||
11065 | explicit MisalignedMember(Expr *E) | |||
11066 | : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} | |||
11067 | ||||
11068 | bool operator==(const MisalignedMember &m) { return this->E == m.E; } | |||
11069 | }; | |||
11070 | /// Small set of gathered accesses to potentially misaligned members | |||
11071 | /// due to the packed attribute. | |||
11072 | SmallVector<MisalignedMember, 4> MisalignedMembers; | |||
11073 | ||||
11074 | /// Adds an expression to the set of gathered misaligned members. | |||
11075 | void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, | |||
11076 | CharUnits Alignment); | |||
11077 | ||||
11078 | public: | |||
11079 | /// Diagnoses the current set of gathered accesses. This typically | |||
11080 | /// happens at full expression level. The set is cleared after emitting the | |||
11081 | /// diagnostics. | |||
11082 | void DiagnoseMisalignedMembers(); | |||
11083 | ||||
11084 | /// This function checks if the expression is in the sef of potentially | |||
11085 | /// misaligned members and it is converted to some pointer type T with lower | |||
11086 | /// or equal alignment requirements. If so it removes it. This is used when | |||
11087 | /// we do not want to diagnose such misaligned access (e.g. in conversions to | |||
11088 | /// void*). | |||
11089 | void DiscardMisalignedMemberAddress(const Type *T, Expr *E); | |||
11090 | ||||
11091 | /// This function calls Action when it determines that E designates a | |||
11092 | /// misaligned member due to the packed attribute. This is used to emit | |||
11093 | /// local diagnostics like in reference binding. | |||
11094 | void RefersToMemberWithReducedAlignment( | |||
11095 | Expr *E, | |||
11096 | llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> | |||
11097 | Action); | |||
11098 | ||||
11099 | /// Describes the reason a calling convention specification was ignored, used | |||
11100 | /// for diagnostics. | |||
11101 | enum class CallingConventionIgnoredReason { | |||
11102 | ForThisTarget = 0, | |||
11103 | VariadicFunction, | |||
11104 | ConstructorDestructor, | |||
11105 | BuiltinFunction | |||
11106 | }; | |||
11107 | }; | |||
11108 | ||||
11109 | /// RAII object that enters a new expression evaluation context. | |||
11110 | class EnterExpressionEvaluationContext { | |||
11111 | Sema &Actions; | |||
11112 | bool Entered = true; | |||
11113 | ||||
11114 | public: | |||
11115 | EnterExpressionEvaluationContext( | |||
11116 | Sema &Actions, Sema::ExpressionEvaluationContext NewContext, | |||
11117 | Decl *LambdaContextDecl = nullptr, | |||
11118 | Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = | |||
11119 | Sema::ExpressionEvaluationContextRecord::EK_Other, | |||
11120 | bool ShouldEnter = true) | |||
11121 | : Actions(Actions), Entered(ShouldEnter) { | |||
11122 | if (Entered) | |||
11123 | Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, | |||
11124 | ExprContext); | |||
11125 | } | |||
11126 | EnterExpressionEvaluationContext( | |||
11127 | Sema &Actions, Sema::ExpressionEvaluationContext NewContext, | |||
11128 | Sema::ReuseLambdaContextDecl_t, | |||
11129 | Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = | |||
11130 | Sema::ExpressionEvaluationContextRecord::EK_Other) | |||
11131 | : Actions(Actions) { | |||
11132 | Actions.PushExpressionEvaluationContext( | |||
11133 | NewContext, Sema::ReuseLambdaContextDecl, ExprContext); | |||
11134 | } | |||
11135 | ||||
11136 | enum InitListTag { InitList }; | |||
11137 | EnterExpressionEvaluationContext(Sema &Actions, InitListTag, | |||
11138 | bool ShouldEnter = true) | |||
11139 | : Actions(Actions), Entered(false) { | |||
11140 | // In C++11 onwards, narrowing checks are performed on the contents of | |||
11141 | // braced-init-lists, even when they occur within unevaluated operands. | |||
11142 | // Therefore we still need to instantiate constexpr functions used in such | |||
11143 | // a context. | |||
11144 | if (ShouldEnter && Actions.isUnevaluatedContext() && | |||
11145 | Actions.getLangOpts().CPlusPlus11) { | |||
11146 | Actions.PushExpressionEvaluationContext( | |||
11147 | Sema::ExpressionEvaluationContext::UnevaluatedList); | |||
11148 | Entered = true; | |||
11149 | } | |||
11150 | } | |||
11151 | ||||
11152 | ~EnterExpressionEvaluationContext() { | |||
11153 | if (Entered) | |||
11154 | Actions.PopExpressionEvaluationContext(); | |||
11155 | } | |||
11156 | }; | |||
11157 | ||||
11158 | DeductionFailureInfo | |||
11159 | MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, | |||
11160 | sema::TemplateDeductionInfo &Info); | |||
11161 | ||||
11162 | /// Contains a late templated function. | |||
11163 | /// Will be parsed at the end of the translation unit, used by Sema & Parser. | |||
11164 | struct LateParsedTemplate { | |||
11165 | CachedTokens Toks; | |||
11166 | /// The template function declaration to be late parsed. | |||
11167 | Decl *D; | |||
11168 | }; | |||
11169 | } // end namespace clang | |||
11170 | ||||
11171 | namespace llvm { | |||
11172 | // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its | |||
11173 | // SourceLocation. | |||
11174 | template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { | |||
11175 | using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; | |||
11176 | using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; | |||
11177 | ||||
11178 | static FunctionDeclAndLoc getEmptyKey() { | |||
11179 | return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; | |||
11180 | } | |||
11181 | ||||
11182 | static FunctionDeclAndLoc getTombstoneKey() { | |||
11183 | return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; | |||
11184 | } | |||
11185 | ||||
11186 | static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { | |||
11187 | return hash_combine(FDBaseInfo::getHashValue(FDL.FD), | |||
11188 | FDL.Loc.getRawEncoding()); | |||
11189 | } | |||
11190 | ||||
11191 | static bool isEqual(const FunctionDeclAndLoc &LHS, | |||
11192 | const FunctionDeclAndLoc &RHS) { | |||
11193 | return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; | |||
11194 | } | |||
11195 | }; | |||
11196 | } // namespace llvm | |||
11197 | ||||
11198 | #endif |