Bug Summary

File:tools/clang/lib/Sema/SemaStmt.cpp
Warning:line 3837, column 7
Potential leak of memory pointed to by field 'DiagStorage'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaStmt.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp

1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTDiagnostic.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/AST/TypeOrdering.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallString.h"
40#include "llvm/ADT/SmallVector.h"
41
42using namespace clang;
43using namespace sema;
44
45StmtResult Sema::ActOnExprStmt(ExprResult FE) {
46 if (FE.isInvalid())
47 return StmtError();
48
49 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
50 /*DiscardedValue*/ true);
51 if (FE.isInvalid())
52 return StmtError();
53
54 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
55 // void expression for its side effects. Conversion to void allows any
56 // operand, even incomplete types.
57
58 // Same thing in for stmt first clause (when expr) and third clause.
59 return StmtResult(FE.getAs<Stmt>());
60}
61
62
63StmtResult Sema::ActOnExprStmtError() {
64 DiscardCleanupsInEvaluationContext();
65 return StmtError();
66}
67
68StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
69 bool HasLeadingEmptyMacro) {
70 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
71}
72
73StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
74 SourceLocation EndLoc) {
75 DeclGroupRef DG = dg.get();
76
77 // If we have an invalid decl, just return an error.
78 if (DG.isNull()) return StmtError();
79
80 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
81}
82
83void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
84 DeclGroupRef DG = dg.get();
85
86 // If we don't have a declaration, or we have an invalid declaration,
87 // just return.
88 if (DG.isNull() || !DG.isSingleDecl())
89 return;
90
91 Decl *decl = DG.getSingleDecl();
92 if (!decl || decl->isInvalidDecl())
93 return;
94
95 // Only variable declarations are permitted.
96 VarDecl *var = dyn_cast<VarDecl>(decl);
97 if (!var) {
98 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
99 decl->setInvalidDecl();
100 return;
101 }
102
103 // foreach variables are never actually initialized in the way that
104 // the parser came up with.
105 var->setInit(nullptr);
106
107 // In ARC, we don't need to retain the iteration variable of a fast
108 // enumeration loop. Rather than actually trying to catch that
109 // during declaration processing, we remove the consequences here.
110 if (getLangOpts().ObjCAutoRefCount) {
111 QualType type = var->getType();
112
113 // Only do this if we inferred the lifetime. Inferred lifetime
114 // will show up as a local qualifier because explicit lifetime
115 // should have shown up as an AttributedType instead.
116 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
117 // Add 'const' and mark the variable as pseudo-strong.
118 var->setType(type.withConst());
119 var->setARCPseudoStrong(true);
120 }
121 }
122}
123
124/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
125/// For '==' and '!=', suggest fixits for '=' or '|='.
126///
127/// Adding a cast to void (or other expression wrappers) will prevent the
128/// warning from firing.
129static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
130 SourceLocation Loc;
131 bool CanAssign;
132 enum { Equality, Inequality, Relational, ThreeWay } Kind;
133
134 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
135 if (!Op->isComparisonOp())
136 return false;
137
138 if (Op->getOpcode() == BO_EQ)
139 Kind = Equality;
140 else if (Op->getOpcode() == BO_NE)
141 Kind = Inequality;
142 else if (Op->getOpcode() == BO_Cmp)
143 Kind = ThreeWay;
144 else {
145 assert(Op->isRelationalOp())(static_cast <bool> (Op->isRelationalOp()) ? void (0
) : __assert_fail ("Op->isRelationalOp()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 145, __extension__ __PRETTY_FUNCTION__))
;
146 Kind = Relational;
147 }
148 Loc = Op->getOperatorLoc();
149 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
150 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
151 switch (Op->getOperator()) {
152 case OO_EqualEqual:
153 Kind = Equality;
154 break;
155 case OO_ExclaimEqual:
156 Kind = Inequality;
157 break;
158 case OO_Less:
159 case OO_Greater:
160 case OO_GreaterEqual:
161 case OO_LessEqual:
162 Kind = Relational;
163 break;
164 case OO_Spaceship:
165 Kind = ThreeWay;
166 break;
167 default:
168 return false;
169 }
170
171 Loc = Op->getOperatorLoc();
172 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
173 } else {
174 // Not a typo-prone comparison.
175 return false;
176 }
177
178 // Suppress warnings when the operator, suspicious as it may be, comes from
179 // a macro expansion.
180 if (S.SourceMgr.isMacroBodyExpansion(Loc))
181 return false;
182
183 S.Diag(Loc, diag::warn_unused_comparison)
184 << (unsigned)Kind << E->getSourceRange();
185
186 // If the LHS is a plausible entity to assign to, provide a fixit hint to
187 // correct common typos.
188 if (CanAssign) {
189 if (Kind == Inequality)
190 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
191 << FixItHint::CreateReplacement(Loc, "|=");
192 else if (Kind == Equality)
193 S.Diag(Loc, diag::note_equality_comparison_to_assign)
194 << FixItHint::CreateReplacement(Loc, "=");
195 }
196
197 return true;
198}
199
200void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
201 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
202 return DiagnoseUnusedExprResult(Label->getSubStmt());
203
204 const Expr *E = dyn_cast_or_null<Expr>(S);
205 if (!E)
206 return;
207
208 // If we are in an unevaluated expression context, then there can be no unused
209 // results because the results aren't expected to be used in the first place.
210 if (isUnevaluatedContext())
211 return;
212
213 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
214 // In most cases, we don't want to warn if the expression is written in a
215 // macro body, or if the macro comes from a system header. If the offending
216 // expression is a call to a function with the warn_unused_result attribute,
217 // we warn no matter the location. Because of the order in which the various
218 // checks need to happen, we factor out the macro-related test here.
219 bool ShouldSuppress =
220 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
221 SourceMgr.isInSystemMacro(ExprLoc);
222
223 const Expr *WarnExpr;
224 SourceLocation Loc;
225 SourceRange R1, R2;
226 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
227 return;
228
229 // If this is a GNU statement expression expanded from a macro, it is probably
230 // unused because it is a function-like macro that can be used as either an
231 // expression or statement. Don't warn, because it is almost certainly a
232 // false positive.
233 if (isa<StmtExpr>(E) && Loc.isMacroID())
234 return;
235
236 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
237 // That macro is frequently used to suppress "unused parameter" warnings,
238 // but its implementation makes clang's -Wunused-value fire. Prevent this.
239 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
240 SourceLocation SpellLoc = Loc;
241 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
242 return;
243 }
244
245 // Okay, we have an unused result. Depending on what the base expression is,
246 // we might want to make a more specific diagnostic. Check for one of these
247 // cases now.
248 unsigned DiagID = diag::warn_unused_expr;
249 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
250 E = Temps->getSubExpr();
251 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
252 E = TempExpr->getSubExpr();
253
254 if (DiagnoseUnusedComparison(*this, E))
255 return;
256
257 E = WarnExpr;
258 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
259 if (E->getType()->isVoidType())
260 return;
261
262 // If the callee has attribute pure, const, or warn_unused_result, warn with
263 // a more specific message to make it clear what is happening. If the call
264 // is written in a macro body, only warn if it has the warn_unused_result
265 // attribute.
266 if (const Decl *FD = CE->getCalleeDecl()) {
267 if (const Attr *A = isa<FunctionDecl>(FD)
268 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
269 : FD->getAttr<WarnUnusedResultAttr>()) {
270 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
271 return;
272 }
273 if (ShouldSuppress)
274 return;
275 if (FD->hasAttr<PureAttr>()) {
276 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
277 return;
278 }
279 if (FD->hasAttr<ConstAttr>()) {
280 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
281 return;
282 }
283 }
284 } else if (ShouldSuppress)
285 return;
286
287 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
288 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
289 Diag(Loc, diag::err_arc_unused_init_message) << R1;
290 return;
291 }
292 const ObjCMethodDecl *MD = ME->getMethodDecl();
293 if (MD) {
294 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
295 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
296 return;
297 }
298 }
299 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
300 const Expr *Source = POE->getSyntacticForm();
301 if (isa<ObjCSubscriptRefExpr>(Source))
302 DiagID = diag::warn_unused_container_subscript_expr;
303 else
304 DiagID = diag::warn_unused_property_expr;
305 } else if (const CXXFunctionalCastExpr *FC
306 = dyn_cast<CXXFunctionalCastExpr>(E)) {
307 const Expr *E = FC->getSubExpr();
308 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
309 E = TE->getSubExpr();
310 if (isa<CXXTemporaryObjectExpr>(E))
311 return;
312 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
313 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
314 if (!RD->getAttr<WarnUnusedAttr>())
315 return;
316 }
317 // Diagnose "(void*) blah" as a typo for "(void) blah".
318 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
319 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
320 QualType T = TI->getType();
321
322 // We really do want to use the non-canonical type here.
323 if (T == Context.VoidPtrTy) {
324 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
325
326 Diag(Loc, diag::warn_unused_voidptr)
327 << FixItHint::CreateRemoval(TL.getStarLoc());
328 return;
329 }
330 }
331
332 if (E->isGLValue() && E->getType().isVolatileQualified()) {
333 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
334 return;
335 }
336
337 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
338}
339
340void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
341 PushCompoundScope(IsStmtExpr);
342}
343
344void Sema::ActOnFinishOfCompoundStmt() {
345 PopCompoundScope();
346}
347
348sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
349 return getCurFunction()->CompoundScopes.back();
350}
351
352StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
353 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
354 const unsigned NumElts = Elts.size();
355
356 // If we're in C89 mode, check that we don't have any decls after stmts. If
357 // so, emit an extension diagnostic.
358 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
359 // Note that __extension__ can be around a decl.
360 unsigned i = 0;
361 // Skip over all declarations.
362 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
363 /*empty*/;
364
365 // We found the end of the list or a statement. Scan for another declstmt.
366 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
367 /*empty*/;
368
369 if (i != NumElts) {
370 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
371 Diag(D->getLocation(), diag::ext_mixed_decls_code);
372 }
373 }
374 // Warn about unused expressions in statements.
375 for (unsigned i = 0; i != NumElts; ++i) {
376 // Ignore statements that are last in a statement expression.
377 if (isStmtExpr && i == NumElts - 1)
378 continue;
379
380 DiagnoseUnusedExprResult(Elts[i]);
381 }
382
383 // Check for suspicious empty body (null statement) in `for' and `while'
384 // statements. Don't do anything for template instantiations, this just adds
385 // noise.
386 if (NumElts != 0 && !CurrentInstantiationScope &&
387 getCurCompoundScope().HasEmptyLoopBodies) {
388 for (unsigned i = 0; i != NumElts - 1; ++i)
389 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
390 }
391
392 return CompoundStmt::Create(Context, Elts, L, R);
393}
394
395StmtResult
396Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
397 SourceLocation DotDotDotLoc, Expr *RHSVal,
398 SourceLocation ColonLoc) {
399 assert(LHSVal && "missing expression in case statement")(static_cast <bool> (LHSVal && "missing expression in case statement"
) ? void (0) : __assert_fail ("LHSVal && \"missing expression in case statement\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 399, __extension__ __PRETTY_FUNCTION__))
;
400
401 if (getCurFunction()->SwitchStack.empty()) {
402 Diag(CaseLoc, diag::err_case_not_in_switch);
403 return StmtError();
404 }
405
406 ExprResult LHS =
407 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
408 if (!getLangOpts().CPlusPlus11)
409 return VerifyIntegerConstantExpression(E);
410 if (Expr *CondExpr =
411 getCurFunction()->SwitchStack.back()->getCond()) {
412 QualType CondType = CondExpr->getType();
413 llvm::APSInt TempVal;
414 return CheckConvertedConstantExpression(E, CondType, TempVal,
415 CCEK_CaseValue);
416 }
417 return ExprError();
418 });
419 if (LHS.isInvalid())
420 return StmtError();
421 LHSVal = LHS.get();
422
423 if (!getLangOpts().CPlusPlus11) {
424 // C99 6.8.4.2p3: The expression shall be an integer constant.
425 // However, GCC allows any evaluatable integer expression.
426 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
427 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
428 if (!LHSVal)
429 return StmtError();
430 }
431
432 // GCC extension: The expression shall be an integer constant.
433
434 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
435 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
436 // Recover from an error by just forgetting about it.
437 }
438 }
439
440 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
441 getLangOpts().CPlusPlus11);
442 if (LHS.isInvalid())
443 return StmtError();
444
445 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
446 getLangOpts().CPlusPlus11)
447 : ExprResult();
448 if (RHS.isInvalid())
449 return StmtError();
450
451 CaseStmt *CS = new (Context)
452 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
453 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
454 return CS;
455}
456
457/// ActOnCaseStmtBody - This installs a statement as the body of a case.
458void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
459 DiagnoseUnusedExprResult(SubStmt);
460
461 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
462 CS->setSubStmt(SubStmt);
463}
464
465StmtResult
466Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
467 Stmt *SubStmt, Scope *CurScope) {
468 DiagnoseUnusedExprResult(SubStmt);
469
470 if (getCurFunction()->SwitchStack.empty()) {
471 Diag(DefaultLoc, diag::err_default_not_in_switch);
472 return SubStmt;
473 }
474
475 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
476 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
477 return DS;
478}
479
480StmtResult
481Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
482 SourceLocation ColonLoc, Stmt *SubStmt) {
483 // If the label was multiply defined, reject it now.
484 if (TheDecl->getStmt()) {
485 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
486 Diag(TheDecl->getLocation(), diag::note_previous_definition);
487 return SubStmt;
488 }
489
490 // Otherwise, things are good. Fill in the declaration and return it.
491 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
492 TheDecl->setStmt(LS);
493 if (!TheDecl->isGnuLocal()) {
494 TheDecl->setLocStart(IdentLoc);
495 if (!TheDecl->isMSAsmLabel()) {
496 // Don't update the location of MS ASM labels. These will result in
497 // a diagnostic, and changing the location here will mess that up.
498 TheDecl->setLocation(IdentLoc);
499 }
500 }
501 return LS;
502}
503
504StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
505 ArrayRef<const Attr*> Attrs,
506 Stmt *SubStmt) {
507 // Fill in the declaration and return it.
508 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
509 return LS;
510}
511
512namespace {
513class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
514 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
515 Sema &SemaRef;
516public:
517 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
518 void VisitBinaryOperator(BinaryOperator *E) {
519 if (E->getOpcode() == BO_Comma)
520 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
521 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
522 }
523};
524}
525
526StmtResult
527Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
528 ConditionResult Cond,
529 Stmt *thenStmt, SourceLocation ElseLoc,
530 Stmt *elseStmt) {
531 if (Cond.isInvalid())
532 Cond = ConditionResult(
533 *this, nullptr,
534 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
535 Context.BoolTy, VK_RValue),
536 IfLoc),
537 false);
538
539 Expr *CondExpr = Cond.get().second;
540 if (!Diags.isIgnored(diag::warn_comma_operator,
541 CondExpr->getExprLoc()))
542 CommaVisitor(*this).Visit(CondExpr);
543
544 if (!elseStmt)
545 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
546 diag::warn_empty_if_body);
547
548 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
549 elseStmt);
550}
551
552StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
553 Stmt *InitStmt, ConditionResult Cond,
554 Stmt *thenStmt, SourceLocation ElseLoc,
555 Stmt *elseStmt) {
556 if (Cond.isInvalid())
557 return StmtError();
558
559 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
560 getCurFunction()->setHasBranchProtectedScope();
561
562 DiagnoseUnusedExprResult(thenStmt);
563 DiagnoseUnusedExprResult(elseStmt);
564
565 return new (Context)
566 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
567 Cond.get().second, thenStmt, ElseLoc, elseStmt);
568}
569
570namespace {
571 struct CaseCompareFunctor {
572 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
573 const llvm::APSInt &RHS) {
574 return LHS.first < RHS;
575 }
576 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
577 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
578 return LHS.first < RHS.first;
579 }
580 bool operator()(const llvm::APSInt &LHS,
581 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
582 return LHS < RHS.first;
583 }
584 };
585}
586
587/// CmpCaseVals - Comparison predicate for sorting case values.
588///
589static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
590 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
591 if (lhs.first < rhs.first)
592 return true;
593
594 if (lhs.first == rhs.first &&
595 lhs.second->getCaseLoc().getRawEncoding()
596 < rhs.second->getCaseLoc().getRawEncoding())
597 return true;
598 return false;
599}
600
601/// CmpEnumVals - Comparison predicate for sorting enumeration values.
602///
603static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
604 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
605{
606 return lhs.first < rhs.first;
607}
608
609/// EqEnumVals - Comparison preficate for uniqing enumeration values.
610///
611static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
612 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
613{
614 return lhs.first == rhs.first;
615}
616
617/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
618/// potentially integral-promoted expression @p expr.
619static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
620 if (const auto *CleanUps = dyn_cast<ExprWithCleanups>(E))
621 E = CleanUps->getSubExpr();
622 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
623 if (ImpCast->getCastKind() != CK_IntegralCast) break;
624 E = ImpCast->getSubExpr();
625 }
626 return E->getType();
627}
628
629ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
630 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
631 Expr *Cond;
632
633 public:
634 SwitchConvertDiagnoser(Expr *Cond)
635 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
636 Cond(Cond) {}
637
638 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
639 QualType T) override {
640 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
641 }
642
643 SemaDiagnosticBuilder diagnoseIncomplete(
644 Sema &S, SourceLocation Loc, QualType T) override {
645 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
646 << T << Cond->getSourceRange();
647 }
648
649 SemaDiagnosticBuilder diagnoseExplicitConv(
650 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
651 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
652 }
653
654 SemaDiagnosticBuilder noteExplicitConv(
655 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
656 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
657 << ConvTy->isEnumeralType() << ConvTy;
658 }
659
660 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
661 QualType T) override {
662 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
663 }
664
665 SemaDiagnosticBuilder noteAmbiguous(
666 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
667 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
668 << ConvTy->isEnumeralType() << ConvTy;
669 }
670
671 SemaDiagnosticBuilder diagnoseConversion(
672 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
673 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 673)
;
674 }
675 } SwitchDiagnoser(Cond);
676
677 ExprResult CondResult =
678 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
679 if (CondResult.isInvalid())
680 return ExprError();
681
682 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
683 return UsualUnaryConversions(CondResult.get());
684}
685
686StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
687 Stmt *InitStmt, ConditionResult Cond) {
688 if (Cond.isInvalid())
689 return StmtError();
690
691 getCurFunction()->setHasBranchIntoScope();
692
693 SwitchStmt *SS = new (Context)
694 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
695 getCurFunction()->SwitchStack.push_back(SS);
696 return SS;
697}
698
699static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
700 Val = Val.extOrTrunc(BitWidth);
701 Val.setIsSigned(IsSigned);
702}
703
704/// Check the specified case value is in range for the given unpromoted switch
705/// type.
706static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
707 unsigned UnpromotedWidth, bool UnpromotedSign) {
708 // If the case value was signed and negative and the switch expression is
709 // unsigned, don't bother to warn: this is implementation-defined behavior.
710 // FIXME: Introduce a second, default-ignored warning for this case?
711 if (UnpromotedWidth < Val.getBitWidth()) {
712 llvm::APSInt ConvVal(Val);
713 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
714 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
715 // FIXME: Use different diagnostics for overflow in conversion to promoted
716 // type versus "switch expression cannot have this value". Use proper
717 // IntRange checking rather than just looking at the unpromoted type here.
718 if (ConvVal != Val)
719 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
720 << ConvVal.toString(10);
721 }
722}
723
724typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
725
726/// Returns true if we should emit a diagnostic about this case expression not
727/// being a part of the enum used in the switch controlling expression.
728static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
729 const EnumDecl *ED,
730 const Expr *CaseExpr,
731 EnumValsTy::iterator &EI,
732 EnumValsTy::iterator &EIEnd,
733 const llvm::APSInt &Val) {
734 if (!ED->isClosed())
735 return false;
736
737 if (const DeclRefExpr *DRE =
738 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
739 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
740 QualType VarType = VD->getType();
741 QualType EnumType = S.Context.getTypeDeclType(ED);
742 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
743 S.Context.hasSameUnqualifiedType(EnumType, VarType))
744 return false;
745 }
746 }
747
748 if (ED->hasAttr<FlagEnumAttr>())
749 return !S.IsValueInFlagEnum(ED, Val, false);
750
751 while (EI != EIEnd && EI->first < Val)
752 EI++;
753
754 if (EI != EIEnd && EI->first == Val)
755 return false;
756
757 return true;
758}
759
760static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
761 const Expr *Case) {
762 QualType CondType = GetTypeBeforeIntegralPromotion(Cond);
763 QualType CaseType = Case->getType();
764
765 const EnumType *CondEnumType = CondType->getAs<EnumType>();
766 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
767 if (!CondEnumType || !CaseEnumType)
768 return;
769
770 // Ignore anonymous enums.
771 if (!CondEnumType->getDecl()->getIdentifier() &&
772 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
773 return;
774 if (!CaseEnumType->getDecl()->getIdentifier() &&
775 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
776 return;
777
778 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
779 return;
780
781 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
782 << CondType << CaseType << Cond->getSourceRange()
783 << Case->getSourceRange();
784}
785
786StmtResult
787Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
788 Stmt *BodyStmt) {
789 SwitchStmt *SS = cast<SwitchStmt>(Switch);
790 assert(SS == getCurFunction()->SwitchStack.back() &&(static_cast <bool> (SS == getCurFunction()->SwitchStack
.back() && "switch stack missing push/pop!") ? void (
0) : __assert_fail ("SS == getCurFunction()->SwitchStack.back() && \"switch stack missing push/pop!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 791, __extension__ __PRETTY_FUNCTION__))
791 "switch stack missing push/pop!")(static_cast <bool> (SS == getCurFunction()->SwitchStack
.back() && "switch stack missing push/pop!") ? void (
0) : __assert_fail ("SS == getCurFunction()->SwitchStack.back() && \"switch stack missing push/pop!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 791, __extension__ __PRETTY_FUNCTION__))
;
792
793 getCurFunction()->SwitchStack.pop_back();
794
795 if (!BodyStmt) return StmtError();
796 SS->setBody(BodyStmt, SwitchLoc);
797
798 Expr *CondExpr = SS->getCond();
799 if (!CondExpr) return StmtError();
800
801 QualType CondType = CondExpr->getType();
802
803 const Expr *CondExprBeforePromotion = CondExpr;
804 QualType CondTypeBeforePromotion =
805 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
806
807 // C++ 6.4.2.p2:
808 // Integral promotions are performed (on the switch condition).
809 //
810 // A case value unrepresentable by the original switch condition
811 // type (before the promotion) doesn't make sense, even when it can
812 // be represented by the promoted type. Therefore we need to find
813 // the pre-promotion type of the switch condition.
814 if (!CondExpr->isTypeDependent()) {
815 // We have already converted the expression to an integral or enumeration
816 // type, when we started the switch statement. If we don't have an
817 // appropriate type now, just return an error.
818 if (!CondType->isIntegralOrEnumerationType())
819 return StmtError();
820
821 if (CondExpr->isKnownToHaveBooleanValue()) {
822 // switch(bool_expr) {...} is often a programmer error, e.g.
823 // switch(n && mask) { ... } // Doh - should be "n & mask".
824 // One can always use an if statement instead of switch(bool_expr).
825 Diag(SwitchLoc, diag::warn_bool_switch_condition)
826 << CondExpr->getSourceRange();
827 }
828 }
829
830 // Get the bitwidth of the switched-on value after promotions. We must
831 // convert the integer case values to this width before comparison.
832 bool HasDependentValue
833 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
834 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
835 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
836
837 // Get the width and signedness that the condition might actually have, for
838 // warning purposes.
839 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
840 // type.
841 unsigned CondWidthBeforePromotion
842 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
843 bool CondIsSignedBeforePromotion
844 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
845
846 // Accumulate all of the case values in a vector so that we can sort them
847 // and detect duplicates. This vector contains the APInt for the case after
848 // it has been converted to the condition type.
849 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
850 CaseValsTy CaseVals;
851
852 // Keep track of any GNU case ranges we see. The APSInt is the low value.
853 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
854 CaseRangesTy CaseRanges;
855
856 DefaultStmt *TheDefaultStmt = nullptr;
857
858 bool CaseListIsErroneous = false;
859
860 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
861 SC = SC->getNextSwitchCase()) {
862
863 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
864 if (TheDefaultStmt) {
865 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
866 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
867
868 // FIXME: Remove the default statement from the switch block so that
869 // we'll return a valid AST. This requires recursing down the AST and
870 // finding it, not something we are set up to do right now. For now,
871 // just lop the entire switch stmt out of the AST.
872 CaseListIsErroneous = true;
873 }
874 TheDefaultStmt = DS;
875
876 } else {
877 CaseStmt *CS = cast<CaseStmt>(SC);
878
879 Expr *Lo = CS->getLHS();
880
881 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
882 HasDependentValue = true;
883 break;
884 }
885
886 checkEnumTypesInSwitchStmt(*this, CondExpr, Lo);
887
888 llvm::APSInt LoVal;
889
890 if (getLangOpts().CPlusPlus11) {
891 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
892 // constant expression of the promoted type of the switch condition.
893 ExprResult ConvLo =
894 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
895 if (ConvLo.isInvalid()) {
896 CaseListIsErroneous = true;
897 continue;
898 }
899 Lo = ConvLo.get();
900 } else {
901 // We already verified that the expression has a i-c-e value (C99
902 // 6.8.4.2p3) - get that value now.
903 LoVal = Lo->EvaluateKnownConstInt(Context);
904
905 // If the LHS is not the same type as the condition, insert an implicit
906 // cast.
907 Lo = DefaultLvalueConversion(Lo).get();
908 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
909 }
910
911 // Check the unconverted value is within the range of possible values of
912 // the switch expression.
913 checkCaseValue(*this, Lo->getLocStart(), LoVal,
914 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
915
916 // Convert the value to the same width/sign as the condition.
917 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
918
919 CS->setLHS(Lo);
920
921 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
922 if (CS->getRHS()) {
923 if (CS->getRHS()->isTypeDependent() ||
924 CS->getRHS()->isValueDependent()) {
925 HasDependentValue = true;
926 break;
927 }
928 CaseRanges.push_back(std::make_pair(LoVal, CS));
929 } else
930 CaseVals.push_back(std::make_pair(LoVal, CS));
931 }
932 }
933
934 if (!HasDependentValue) {
935 // If we don't have a default statement, check whether the
936 // condition is constant.
937 llvm::APSInt ConstantCondValue;
938 bool HasConstantCond = false;
939 if (!HasDependentValue && !TheDefaultStmt) {
940 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
941 Expr::SE_AllowSideEffects);
942 assert(!HasConstantCond ||(static_cast <bool> (!HasConstantCond || (ConstantCondValue
.getBitWidth() == CondWidth && ConstantCondValue.isSigned
() == CondIsSigned)) ? void (0) : __assert_fail ("!HasConstantCond || (ConstantCondValue.getBitWidth() == CondWidth && ConstantCondValue.isSigned() == CondIsSigned)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 944, __extension__ __PRETTY_FUNCTION__))
943 (ConstantCondValue.getBitWidth() == CondWidth &&(static_cast <bool> (!HasConstantCond || (ConstantCondValue
.getBitWidth() == CondWidth && ConstantCondValue.isSigned
() == CondIsSigned)) ? void (0) : __assert_fail ("!HasConstantCond || (ConstantCondValue.getBitWidth() == CondWidth && ConstantCondValue.isSigned() == CondIsSigned)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 944, __extension__ __PRETTY_FUNCTION__))
944 ConstantCondValue.isSigned() == CondIsSigned))(static_cast <bool> (!HasConstantCond || (ConstantCondValue
.getBitWidth() == CondWidth && ConstantCondValue.isSigned
() == CondIsSigned)) ? void (0) : __assert_fail ("!HasConstantCond || (ConstantCondValue.getBitWidth() == CondWidth && ConstantCondValue.isSigned() == CondIsSigned)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 944, __extension__ __PRETTY_FUNCTION__))
;
945 }
946 bool ShouldCheckConstantCond = HasConstantCond;
947
948 // Sort all the scalar case values so we can easily detect duplicates.
949 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
950
951 if (!CaseVals.empty()) {
952 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
953 if (ShouldCheckConstantCond &&
954 CaseVals[i].first == ConstantCondValue)
955 ShouldCheckConstantCond = false;
956
957 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
958 // If we have a duplicate, report it.
959 // First, determine if either case value has a name
960 StringRef PrevString, CurrString;
961 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
962 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
963 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
964 PrevString = DeclRef->getDecl()->getName();
965 }
966 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
967 CurrString = DeclRef->getDecl()->getName();
968 }
969 SmallString<16> CaseValStr;
970 CaseVals[i-1].first.toString(CaseValStr);
971
972 if (PrevString == CurrString)
973 Diag(CaseVals[i].second->getLHS()->getLocStart(),
974 diag::err_duplicate_case) <<
975 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
976 else
977 Diag(CaseVals[i].second->getLHS()->getLocStart(),
978 diag::err_duplicate_case_differing_expr) <<
979 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
980 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
981 CaseValStr;
982
983 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
984 diag::note_duplicate_case_prev);
985 // FIXME: We really want to remove the bogus case stmt from the
986 // substmt, but we have no way to do this right now.
987 CaseListIsErroneous = true;
988 }
989 }
990 }
991
992 // Detect duplicate case ranges, which usually don't exist at all in
993 // the first place.
994 if (!CaseRanges.empty()) {
995 // Sort all the case ranges by their low value so we can easily detect
996 // overlaps between ranges.
997 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
998
999 // Scan the ranges, computing the high values and removing empty ranges.
1000 std::vector<llvm::APSInt> HiVals;
1001 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1002 llvm::APSInt &LoVal = CaseRanges[i].first;
1003 CaseStmt *CR = CaseRanges[i].second;
1004 Expr *Hi = CR->getRHS();
1005 llvm::APSInt HiVal;
1006
1007 if (getLangOpts().CPlusPlus11) {
1008 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
1009 // constant expression of the promoted type of the switch condition.
1010 ExprResult ConvHi =
1011 CheckConvertedConstantExpression(Hi, CondType, HiVal,
1012 CCEK_CaseValue);
1013 if (ConvHi.isInvalid()) {
1014 CaseListIsErroneous = true;
1015 continue;
1016 }
1017 Hi = ConvHi.get();
1018 } else {
1019 HiVal = Hi->EvaluateKnownConstInt(Context);
1020
1021 // If the RHS is not the same type as the condition, insert an
1022 // implicit cast.
1023 Hi = DefaultLvalueConversion(Hi).get();
1024 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
1025 }
1026
1027 // Check the unconverted value is within the range of possible values of
1028 // the switch expression.
1029 checkCaseValue(*this, Hi->getLocStart(), HiVal,
1030 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1031
1032 // Convert the value to the same width/sign as the condition.
1033 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1034
1035 CR->setRHS(Hi);
1036
1037 // If the low value is bigger than the high value, the case is empty.
1038 if (LoVal > HiVal) {
1039 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
1040 << SourceRange(CR->getLHS()->getLocStart(),
1041 Hi->getLocEnd());
1042 CaseRanges.erase(CaseRanges.begin()+i);
1043 --i;
1044 --e;
1045 continue;
1046 }
1047
1048 if (ShouldCheckConstantCond &&
1049 LoVal <= ConstantCondValue &&
1050 ConstantCondValue <= HiVal)
1051 ShouldCheckConstantCond = false;
1052
1053 HiVals.push_back(HiVal);
1054 }
1055
1056 // Rescan the ranges, looking for overlap with singleton values and other
1057 // ranges. Since the range list is sorted, we only need to compare case
1058 // ranges with their neighbors.
1059 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1060 llvm::APSInt &CRLo = CaseRanges[i].first;
1061 llvm::APSInt &CRHi = HiVals[i];
1062 CaseStmt *CR = CaseRanges[i].second;
1063
1064 // Check to see whether the case range overlaps with any
1065 // singleton cases.
1066 CaseStmt *OverlapStmt = nullptr;
1067 llvm::APSInt OverlapVal(32);
1068
1069 // Find the smallest value >= the lower bound. If I is in the
1070 // case range, then we have overlap.
1071 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1072 CaseVals.end(), CRLo,
1073 CaseCompareFunctor());
1074 if (I != CaseVals.end() && I->first < CRHi) {
1075 OverlapVal = I->first; // Found overlap with scalar.
1076 OverlapStmt = I->second;
1077 }
1078
1079 // Find the smallest value bigger than the upper bound.
1080 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1081 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1082 OverlapVal = (I-1)->first; // Found overlap with scalar.
1083 OverlapStmt = (I-1)->second;
1084 }
1085
1086 // Check to see if this case stmt overlaps with the subsequent
1087 // case range.
1088 if (i && CRLo <= HiVals[i-1]) {
1089 OverlapVal = HiVals[i-1]; // Found overlap with range.
1090 OverlapStmt = CaseRanges[i-1].second;
1091 }
1092
1093 if (OverlapStmt) {
1094 // If we have a duplicate, report it.
1095 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1096 << OverlapVal.toString(10);
1097 Diag(OverlapStmt->getLHS()->getLocStart(),
1098 diag::note_duplicate_case_prev);
1099 // FIXME: We really want to remove the bogus case stmt from the
1100 // substmt, but we have no way to do this right now.
1101 CaseListIsErroneous = true;
1102 }
1103 }
1104 }
1105
1106 // Complain if we have a constant condition and we didn't find a match.
1107 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1108 // TODO: it would be nice if we printed enums as enums, chars as
1109 // chars, etc.
1110 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1111 << ConstantCondValue.toString(10)
1112 << CondExpr->getSourceRange();
1113 }
1114
1115 // Check to see if switch is over an Enum and handles all of its
1116 // values. We only issue a warning if there is not 'default:', but
1117 // we still do the analysis to preserve this information in the AST
1118 // (which can be used by flow-based analyes).
1119 //
1120 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1121
1122 // If switch has default case, then ignore it.
1123 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1124 ET->getDecl()->isCompleteDefinition()) {
1125 const EnumDecl *ED = ET->getDecl();
1126 EnumValsTy EnumVals;
1127
1128 // Gather all enum values, set their type and sort them,
1129 // allowing easier comparison with CaseVals.
1130 for (auto *EDI : ED->enumerators()) {
1131 llvm::APSInt Val = EDI->getInitVal();
1132 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1133 EnumVals.push_back(std::make_pair(Val, EDI));
1134 }
1135 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1136 auto EI = EnumVals.begin(), EIEnd =
1137 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1138
1139 // See which case values aren't in enum.
1140 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1141 CI != CaseVals.end(); CI++) {
1142 Expr *CaseExpr = CI->second->getLHS();
1143 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1144 CI->first))
1145 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1146 << CondTypeBeforePromotion;
1147 }
1148
1149 // See which of case ranges aren't in enum
1150 EI = EnumVals.begin();
1151 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1152 RI != CaseRanges.end(); RI++) {
1153 Expr *CaseExpr = RI->second->getLHS();
1154 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1155 RI->first))
1156 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1157 << CondTypeBeforePromotion;
1158
1159 llvm::APSInt Hi =
1160 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1161 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1162
1163 CaseExpr = RI->second->getRHS();
1164 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1165 Hi))
1166 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1167 << CondTypeBeforePromotion;
1168 }
1169
1170 // Check which enum vals aren't in switch
1171 auto CI = CaseVals.begin();
1172 auto RI = CaseRanges.begin();
1173 bool hasCasesNotInSwitch = false;
1174
1175 SmallVector<DeclarationName,8> UnhandledNames;
1176
1177 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1178 // Drop unneeded case values
1179 while (CI != CaseVals.end() && CI->first < EI->first)
1180 CI++;
1181
1182 if (CI != CaseVals.end() && CI->first == EI->first)
1183 continue;
1184
1185 // Drop unneeded case ranges
1186 for (; RI != CaseRanges.end(); RI++) {
1187 llvm::APSInt Hi =
1188 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1189 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1190 if (EI->first <= Hi)
1191 break;
1192 }
1193
1194 if (RI == CaseRanges.end() || EI->first < RI->first) {
1195 hasCasesNotInSwitch = true;
1196 UnhandledNames.push_back(EI->second->getDeclName());
1197 }
1198 }
1199
1200 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1201 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1202
1203 // Produce a nice diagnostic if multiple values aren't handled.
1204 if (!UnhandledNames.empty()) {
1205 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1206 TheDefaultStmt ? diag::warn_def_missing_case
1207 : diag::warn_missing_case)
1208 << (int)UnhandledNames.size();
1209
1210 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1211 I != E; ++I)
1212 DB << UnhandledNames[I];
1213 }
1214
1215 if (!hasCasesNotInSwitch)
1216 SS->setAllEnumCasesCovered();
1217 }
1218 }
1219
1220 if (BodyStmt)
1221 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1222 diag::warn_empty_switch_body);
1223
1224 // FIXME: If the case list was broken is some way, we don't have a good system
1225 // to patch it up. Instead, just return the whole substmt as broken.
1226 if (CaseListIsErroneous)
1227 return StmtError();
1228
1229 return SS;
1230}
1231
1232void
1233Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1234 Expr *SrcExpr) {
1235 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1236 return;
1237
1238 if (const EnumType *ET = DstType->getAs<EnumType>())
1239 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1240 SrcType->isIntegerType()) {
1241 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1242 SrcExpr->isIntegerConstantExpr(Context)) {
1243 // Get the bitwidth of the enum value before promotions.
1244 unsigned DstWidth = Context.getIntWidth(DstType);
1245 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1246
1247 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1248 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1249 const EnumDecl *ED = ET->getDecl();
1250
1251 if (!ED->isClosed())
1252 return;
1253
1254 if (ED->hasAttr<FlagEnumAttr>()) {
1255 if (!IsValueInFlagEnum(ED, RhsVal, true))
1256 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1257 << DstType.getUnqualifiedType();
1258 } else {
1259 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1260 EnumValsTy;
1261 EnumValsTy EnumVals;
1262
1263 // Gather all enum values, set their type and sort them,
1264 // allowing easier comparison with rhs constant.
1265 for (auto *EDI : ED->enumerators()) {
1266 llvm::APSInt Val = EDI->getInitVal();
1267 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1268 EnumVals.push_back(std::make_pair(Val, EDI));
1269 }
1270 if (EnumVals.empty())
1271 return;
1272 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1273 EnumValsTy::iterator EIend =
1274 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1275
1276 // See which values aren't in the enum.
1277 EnumValsTy::const_iterator EI = EnumVals.begin();
1278 while (EI != EIend && EI->first < RhsVal)
1279 EI++;
1280 if (EI == EIend || EI->first != RhsVal) {
1281 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1282 << DstType.getUnqualifiedType();
1283 }
1284 }
1285 }
1286 }
1287}
1288
1289StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1290 Stmt *Body) {
1291 if (Cond.isInvalid())
1292 return StmtError();
1293
1294 auto CondVal = Cond.get();
1295 CheckBreakContinueBinding(CondVal.second);
1296
1297 if (CondVal.second &&
1298 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1299 CommaVisitor(*this).Visit(CondVal.second);
1300
1301 DiagnoseUnusedExprResult(Body);
1302
1303 if (isa<NullStmt>(Body))
1304 getCurCompoundScope().setHasEmptyLoopBodies();
1305
1306 return new (Context)
1307 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
1308}
1309
1310StmtResult
1311Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1312 SourceLocation WhileLoc, SourceLocation CondLParen,
1313 Expr *Cond, SourceLocation CondRParen) {
1314 assert(Cond && "ActOnDoStmt(): missing expression")(static_cast <bool> (Cond && "ActOnDoStmt(): missing expression"
) ? void (0) : __assert_fail ("Cond && \"ActOnDoStmt(): missing expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 1314, __extension__ __PRETTY_FUNCTION__))
;
1315
1316 CheckBreakContinueBinding(Cond);
1317 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1318 if (CondResult.isInvalid())
1319 return StmtError();
1320 Cond = CondResult.get();
1321
1322 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1323 if (CondResult.isInvalid())
1324 return StmtError();
1325 Cond = CondResult.get();
1326
1327 DiagnoseUnusedExprResult(Body);
1328
1329 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1330}
1331
1332namespace {
1333 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1334 using DeclSetVector =
1335 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1336 llvm::SmallPtrSet<VarDecl *, 8>>;
1337
1338 // This visitor will traverse a conditional statement and store all
1339 // the evaluated decls into a vector. Simple is set to true if none
1340 // of the excluded constructs are used.
1341 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1342 DeclSetVector &Decls;
1343 SmallVectorImpl<SourceRange> &Ranges;
1344 bool Simple;
1345 public:
1346 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1347
1348 DeclExtractor(Sema &S, DeclSetVector &Decls,
1349 SmallVectorImpl<SourceRange> &Ranges) :
1350 Inherited(S.Context),
1351 Decls(Decls),
1352 Ranges(Ranges),
1353 Simple(true) {}
1354
1355 bool isSimple() { return Simple; }
1356
1357 // Replaces the method in EvaluatedExprVisitor.
1358 void VisitMemberExpr(MemberExpr* E) {
1359 Simple = false;
1360 }
1361
1362 // Any Stmt not whitelisted will cause the condition to be marked complex.
1363 void VisitStmt(Stmt *S) {
1364 Simple = false;
1365 }
1366
1367 void VisitBinaryOperator(BinaryOperator *E) {
1368 Visit(E->getLHS());
1369 Visit(E->getRHS());
1370 }
1371
1372 void VisitCastExpr(CastExpr *E) {
1373 Visit(E->getSubExpr());
1374 }
1375
1376 void VisitUnaryOperator(UnaryOperator *E) {
1377 // Skip checking conditionals with derefernces.
1378 if (E->getOpcode() == UO_Deref)
1379 Simple = false;
1380 else
1381 Visit(E->getSubExpr());
1382 }
1383
1384 void VisitConditionalOperator(ConditionalOperator *E) {
1385 Visit(E->getCond());
1386 Visit(E->getTrueExpr());
1387 Visit(E->getFalseExpr());
1388 }
1389
1390 void VisitParenExpr(ParenExpr *E) {
1391 Visit(E->getSubExpr());
1392 }
1393
1394 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1395 Visit(E->getOpaqueValue()->getSourceExpr());
1396 Visit(E->getFalseExpr());
1397 }
1398
1399 void VisitIntegerLiteral(IntegerLiteral *E) { }
1400 void VisitFloatingLiteral(FloatingLiteral *E) { }
1401 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1402 void VisitCharacterLiteral(CharacterLiteral *E) { }
1403 void VisitGNUNullExpr(GNUNullExpr *E) { }
1404 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1405
1406 void VisitDeclRefExpr(DeclRefExpr *E) {
1407 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1408 if (!VD) return;
1409
1410 Ranges.push_back(E->getSourceRange());
1411
1412 Decls.insert(VD);
1413 }
1414
1415 }; // end class DeclExtractor
1416
1417 // DeclMatcher checks to see if the decls are used in a non-evaluated
1418 // context.
1419 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1420 DeclSetVector &Decls;
1421 bool FoundDecl;
1422
1423 public:
1424 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1425
1426 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1427 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1428 if (!Statement) return;
1429
1430 Visit(Statement);
1431 }
1432
1433 void VisitReturnStmt(ReturnStmt *S) {
1434 FoundDecl = true;
1435 }
1436
1437 void VisitBreakStmt(BreakStmt *S) {
1438 FoundDecl = true;
1439 }
1440
1441 void VisitGotoStmt(GotoStmt *S) {
1442 FoundDecl = true;
1443 }
1444
1445 void VisitCastExpr(CastExpr *E) {
1446 if (E->getCastKind() == CK_LValueToRValue)
1447 CheckLValueToRValueCast(E->getSubExpr());
1448 else
1449 Visit(E->getSubExpr());
1450 }
1451
1452 void CheckLValueToRValueCast(Expr *E) {
1453 E = E->IgnoreParenImpCasts();
1454
1455 if (isa<DeclRefExpr>(E)) {
1456 return;
1457 }
1458
1459 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1460 Visit(CO->getCond());
1461 CheckLValueToRValueCast(CO->getTrueExpr());
1462 CheckLValueToRValueCast(CO->getFalseExpr());
1463 return;
1464 }
1465
1466 if (BinaryConditionalOperator *BCO =
1467 dyn_cast<BinaryConditionalOperator>(E)) {
1468 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1469 CheckLValueToRValueCast(BCO->getFalseExpr());
1470 return;
1471 }
1472
1473 Visit(E);
1474 }
1475
1476 void VisitDeclRefExpr(DeclRefExpr *E) {
1477 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1478 if (Decls.count(VD))
1479 FoundDecl = true;
1480 }
1481
1482 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1483 // Only need to visit the semantics for POE.
1484 // SyntaticForm doesn't really use the Decal.
1485 for (auto *S : POE->semantics()) {
1486 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1487 // Look past the OVE into the expression it binds.
1488 Visit(OVE->getSourceExpr());
1489 else
1490 Visit(S);
1491 }
1492 }
1493
1494 bool FoundDeclInUse() { return FoundDecl; }
1495
1496 }; // end class DeclMatcher
1497
1498 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1499 Expr *Third, Stmt *Body) {
1500 // Condition is empty
1501 if (!Second) return;
1502
1503 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1504 Second->getLocStart()))
1505 return;
1506
1507 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1508 DeclSetVector Decls;
1509 SmallVector<SourceRange, 10> Ranges;
1510 DeclExtractor DE(S, Decls, Ranges);
1511 DE.Visit(Second);
1512
1513 // Don't analyze complex conditionals.
1514 if (!DE.isSimple()) return;
1515
1516 // No decls found.
1517 if (Decls.size() == 0) return;
1518
1519 // Don't warn on volatile, static, or global variables.
1520 for (auto *VD : Decls)
1521 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1522 return;
1523
1524 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1525 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1526 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1527 return;
1528
1529 // Load decl names into diagnostic.
1530 if (Decls.size() > 4) {
1531 PDiag << 0;
1532 } else {
1533 PDiag << (unsigned)Decls.size();
1534 for (auto *VD : Decls)
1535 PDiag << VD->getDeclName();
1536 }
1537
1538 for (auto Range : Ranges)
1539 PDiag << Range;
1540
1541 S.Diag(Ranges.begin()->getBegin(), PDiag);
1542 }
1543
1544 // If Statement is an incemement or decrement, return true and sets the
1545 // variables Increment and DRE.
1546 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1547 DeclRefExpr *&DRE) {
1548 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1549 if (!Cleanups->cleanupsHaveSideEffects())
1550 Statement = Cleanups->getSubExpr();
1551
1552 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1553 switch (UO->getOpcode()) {
1554 default: return false;
1555 case UO_PostInc:
1556 case UO_PreInc:
1557 Increment = true;
1558 break;
1559 case UO_PostDec:
1560 case UO_PreDec:
1561 Increment = false;
1562 break;
1563 }
1564 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1565 return DRE;
1566 }
1567
1568 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1569 FunctionDecl *FD = Call->getDirectCallee();
1570 if (!FD || !FD->isOverloadedOperator()) return false;
1571 switch (FD->getOverloadedOperator()) {
1572 default: return false;
1573 case OO_PlusPlus:
1574 Increment = true;
1575 break;
1576 case OO_MinusMinus:
1577 Increment = false;
1578 break;
1579 }
1580 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1581 return DRE;
1582 }
1583
1584 return false;
1585 }
1586
1587 // A visitor to determine if a continue or break statement is a
1588 // subexpression.
1589 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1590 SourceLocation BreakLoc;
1591 SourceLocation ContinueLoc;
1592 bool InSwitch = false;
1593
1594 public:
1595 BreakContinueFinder(Sema &S, const Stmt* Body) :
1596 Inherited(S.Context) {
1597 Visit(Body);
1598 }
1599
1600 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1601
1602 void VisitContinueStmt(const ContinueStmt* E) {
1603 ContinueLoc = E->getContinueLoc();
1604 }
1605
1606 void VisitBreakStmt(const BreakStmt* E) {
1607 if (!InSwitch)
1608 BreakLoc = E->getBreakLoc();
1609 }
1610
1611 void VisitSwitchStmt(const SwitchStmt* S) {
1612 if (const Stmt *Init = S->getInit())
1613 Visit(Init);
1614 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1615 Visit(CondVar);
1616 if (const Stmt *Cond = S->getCond())
1617 Visit(Cond);
1618
1619 // Don't return break statements from the body of a switch.
1620 InSwitch = true;
1621 if (const Stmt *Body = S->getBody())
1622 Visit(Body);
1623 InSwitch = false;
1624 }
1625
1626 void VisitForStmt(const ForStmt *S) {
1627 // Only visit the init statement of a for loop; the body
1628 // has a different break/continue scope.
1629 if (const Stmt *Init = S->getInit())
1630 Visit(Init);
1631 }
1632
1633 void VisitWhileStmt(const WhileStmt *) {
1634 // Do nothing; the children of a while loop have a different
1635 // break/continue scope.
1636 }
1637
1638 void VisitDoStmt(const DoStmt *) {
1639 // Do nothing; the children of a while loop have a different
1640 // break/continue scope.
1641 }
1642
1643 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1644 // Only visit the initialization of a for loop; the body
1645 // has a different break/continue scope.
1646 if (const Stmt *Range = S->getRangeStmt())
1647 Visit(Range);
1648 if (const Stmt *Begin = S->getBeginStmt())
1649 Visit(Begin);
1650 if (const Stmt *End = S->getEndStmt())
1651 Visit(End);
1652 }
1653
1654 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1655 // Only visit the initialization of a for loop; the body
1656 // has a different break/continue scope.
1657 if (const Stmt *Element = S->getElement())
1658 Visit(Element);
1659 if (const Stmt *Collection = S->getCollection())
1660 Visit(Collection);
1661 }
1662
1663 bool ContinueFound() { return ContinueLoc.isValid(); }
1664 bool BreakFound() { return BreakLoc.isValid(); }
1665 SourceLocation GetContinueLoc() { return ContinueLoc; }
1666 SourceLocation GetBreakLoc() { return BreakLoc; }
1667
1668 }; // end class BreakContinueFinder
1669
1670 // Emit a warning when a loop increment/decrement appears twice per loop
1671 // iteration. The conditions which trigger this warning are:
1672 // 1) The last statement in the loop body and the third expression in the
1673 // for loop are both increment or both decrement of the same variable
1674 // 2) No continue statements in the loop body.
1675 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1676 // Return when there is nothing to check.
1677 if (!Body || !Third) return;
1678
1679 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1680 Third->getLocStart()))
1681 return;
1682
1683 // Get the last statement from the loop body.
1684 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1685 if (!CS || CS->body_empty()) return;
1686 Stmt *LastStmt = CS->body_back();
1687 if (!LastStmt) return;
1688
1689 bool LoopIncrement, LastIncrement;
1690 DeclRefExpr *LoopDRE, *LastDRE;
1691
1692 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1693 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1694
1695 // Check that the two statements are both increments or both decrements
1696 // on the same variable.
1697 if (LoopIncrement != LastIncrement ||
1698 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1699
1700 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1701
1702 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1703 << LastDRE->getDecl() << LastIncrement;
1704 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1705 << LoopIncrement;
1706 }
1707
1708} // end namespace
1709
1710
1711void Sema::CheckBreakContinueBinding(Expr *E) {
1712 if (!E || getLangOpts().CPlusPlus)
1713 return;
1714 BreakContinueFinder BCFinder(*this, E);
1715 Scope *BreakParent = CurScope->getBreakParent();
1716 if (BCFinder.BreakFound() && BreakParent) {
1717 if (BreakParent->getFlags() & Scope::SwitchScope) {
1718 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1719 } else {
1720 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1721 << "break";
1722 }
1723 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1724 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1725 << "continue";
1726 }
1727}
1728
1729StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1730 Stmt *First, ConditionResult Second,
1731 FullExprArg third, SourceLocation RParenLoc,
1732 Stmt *Body) {
1733 if (Second.isInvalid())
1734 return StmtError();
1735
1736 if (!getLangOpts().CPlusPlus) {
1737 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1738 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1739 // declare identifiers for objects having storage class 'auto' or
1740 // 'register'.
1741 for (auto *DI : DS->decls()) {
1742 VarDecl *VD = dyn_cast<VarDecl>(DI);
1743 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1744 VD = nullptr;
1745 if (!VD) {
1746 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1747 DI->setInvalidDecl();
1748 }
1749 }
1750 }
1751 }
1752
1753 CheckBreakContinueBinding(Second.get().second);
1754 CheckBreakContinueBinding(third.get());
1755
1756 if (!Second.get().first)
1757 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1758 Body);
1759 CheckForRedundantIteration(*this, third.get(), Body);
1760
1761 if (Second.get().second &&
1762 !Diags.isIgnored(diag::warn_comma_operator,
1763 Second.get().second->getExprLoc()))
1764 CommaVisitor(*this).Visit(Second.get().second);
1765
1766 Expr *Third = third.release().getAs<Expr>();
1767
1768 DiagnoseUnusedExprResult(First);
1769 DiagnoseUnusedExprResult(Third);
1770 DiagnoseUnusedExprResult(Body);
1771
1772 if (isa<NullStmt>(Body))
1773 getCurCompoundScope().setHasEmptyLoopBodies();
1774
1775 return new (Context)
1776 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1777 Body, ForLoc, LParenLoc, RParenLoc);
1778}
1779
1780/// In an Objective C collection iteration statement:
1781/// for (x in y)
1782/// x can be an arbitrary l-value expression. Bind it up as a
1783/// full-expression.
1784StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1785 // Reduce placeholder expressions here. Note that this rejects the
1786 // use of pseudo-object l-values in this position.
1787 ExprResult result = CheckPlaceholderExpr(E);
1788 if (result.isInvalid()) return StmtError();
1789 E = result.get();
1790
1791 ExprResult FullExpr = ActOnFinishFullExpr(E);
1792 if (FullExpr.isInvalid())
1793 return StmtError();
1794 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1795}
1796
1797ExprResult
1798Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1799 if (!collection)
1800 return ExprError();
1801
1802 ExprResult result = CorrectDelayedTyposInExpr(collection);
1803 if (!result.isUsable())
1804 return ExprError();
1805 collection = result.get();
1806
1807 // Bail out early if we've got a type-dependent expression.
1808 if (collection->isTypeDependent()) return collection;
1809
1810 // Perform normal l-value conversion.
1811 result = DefaultFunctionArrayLvalueConversion(collection);
1812 if (result.isInvalid())
1813 return ExprError();
1814 collection = result.get();
1815
1816 // The operand needs to have object-pointer type.
1817 // TODO: should we do a contextual conversion?
1818 const ObjCObjectPointerType *pointerType =
1819 collection->getType()->getAs<ObjCObjectPointerType>();
1820 if (!pointerType)
1821 return Diag(forLoc, diag::err_collection_expr_type)
1822 << collection->getType() << collection->getSourceRange();
1823
1824 // Check that the operand provides
1825 // - countByEnumeratingWithState:objects:count:
1826 const ObjCObjectType *objectType = pointerType->getObjectType();
1827 ObjCInterfaceDecl *iface = objectType->getInterface();
1828
1829 // If we have a forward-declared type, we can't do this check.
1830 // Under ARC, it is an error not to have a forward-declared class.
1831 if (iface &&
1832 (getLangOpts().ObjCAutoRefCount
1833 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1834 diag::err_arc_collection_forward, collection)
1835 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1836 // Otherwise, if we have any useful type information, check that
1837 // the type declares the appropriate method.
1838 } else if (iface || !objectType->qual_empty()) {
1839 IdentifierInfo *selectorIdents[] = {
1840 &Context.Idents.get("countByEnumeratingWithState"),
1841 &Context.Idents.get("objects"),
1842 &Context.Idents.get("count")
1843 };
1844 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1845
1846 ObjCMethodDecl *method = nullptr;
1847
1848 // If there's an interface, look in both the public and private APIs.
1849 if (iface) {
1850 method = iface->lookupInstanceMethod(selector);
1851 if (!method) method = iface->lookupPrivateMethod(selector);
1852 }
1853
1854 // Also check protocol qualifiers.
1855 if (!method)
1856 method = LookupMethodInQualifiedType(selector, pointerType,
1857 /*instance*/ true);
1858
1859 // If we didn't find it anywhere, give up.
1860 if (!method) {
1861 Diag(forLoc, diag::warn_collection_expr_type)
1862 << collection->getType() << selector << collection->getSourceRange();
1863 }
1864
1865 // TODO: check for an incompatible signature?
1866 }
1867
1868 // Wrap up any cleanups in the expression.
1869 return collection;
1870}
1871
1872StmtResult
1873Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1874 Stmt *First, Expr *collection,
1875 SourceLocation RParenLoc) {
1876 getCurFunction()->setHasBranchProtectedScope();
1877
1878 ExprResult CollectionExprResult =
1879 CheckObjCForCollectionOperand(ForLoc, collection);
1880
1881 if (First) {
1882 QualType FirstType;
1883 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1884 if (!DS->isSingleDecl())
1885 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1886 diag::err_toomany_element_decls));
1887
1888 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1889 if (!D || D->isInvalidDecl())
1890 return StmtError();
1891
1892 FirstType = D->getType();
1893 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1894 // declare identifiers for objects having storage class 'auto' or
1895 // 'register'.
1896 if (!D->hasLocalStorage())
1897 return StmtError(Diag(D->getLocation(),
1898 diag::err_non_local_variable_decl_in_for));
1899
1900 // If the type contained 'auto', deduce the 'auto' to 'id'.
1901 if (FirstType->getContainedAutoType()) {
1902 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1903 VK_RValue);
1904 Expr *DeducedInit = &OpaqueId;
1905 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1906 DAR_Failed)
1907 DiagnoseAutoDeductionFailure(D, DeducedInit);
1908 if (FirstType.isNull()) {
1909 D->setInvalidDecl();
1910 return StmtError();
1911 }
1912
1913 D->setType(FirstType);
1914
1915 if (!inTemplateInstantiation()) {
1916 SourceLocation Loc =
1917 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1918 Diag(Loc, diag::warn_auto_var_is_id)
1919 << D->getDeclName();
1920 }
1921 }
1922
1923 } else {
1924 Expr *FirstE = cast<Expr>(First);
1925 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1926 return StmtError(Diag(First->getLocStart(),
1927 diag::err_selector_element_not_lvalue)
1928 << First->getSourceRange());
1929
1930 FirstType = static_cast<Expr*>(First)->getType();
1931 if (FirstType.isConstQualified())
1932 Diag(ForLoc, diag::err_selector_element_const_type)
1933 << FirstType << First->getSourceRange();
1934 }
1935 if (!FirstType->isDependentType() &&
1936 !FirstType->isObjCObjectPointerType() &&
1937 !FirstType->isBlockPointerType())
1938 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1939 << FirstType << First->getSourceRange());
1940 }
1941
1942 if (CollectionExprResult.isInvalid())
1943 return StmtError();
1944
1945 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1946 if (CollectionExprResult.isInvalid())
1947 return StmtError();
1948
1949 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1950 nullptr, ForLoc, RParenLoc);
1951}
1952
1953/// Finish building a variable declaration for a for-range statement.
1954/// \return true if an error occurs.
1955static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1956 SourceLocation Loc, int DiagID) {
1957 if (Decl->getType()->isUndeducedType()) {
1958 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1959 if (!Res.isUsable()) {
1960 Decl->setInvalidDecl();
1961 return true;
1962 }
1963 Init = Res.get();
1964 }
1965
1966 // Deduce the type for the iterator variable now rather than leaving it to
1967 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1968 QualType InitType;
1969 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1970 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1971 Sema::DAR_Failed)
1972 SemaRef.Diag(Loc, DiagID) << Init->getType();
1973 if (InitType.isNull()) {
1974 Decl->setInvalidDecl();
1975 return true;
1976 }
1977 Decl->setType(InitType);
1978
1979 // In ARC, infer lifetime.
1980 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1981 // we're doing the equivalent of fast iteration.
1982 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1983 SemaRef.inferObjCARCLifetime(Decl))
1984 Decl->setInvalidDecl();
1985
1986 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1987 SemaRef.FinalizeDeclaration(Decl);
1988 SemaRef.CurContext->addHiddenDecl(Decl);
1989 return false;
1990}
1991
1992namespace {
1993// An enum to represent whether something is dealing with a call to begin()
1994// or a call to end() in a range-based for loop.
1995enum BeginEndFunction {
1996 BEF_begin,
1997 BEF_end
1998};
1999
2000/// Produce a note indicating which begin/end function was implicitly called
2001/// by a C++11 for-range statement. This is often not obvious from the code,
2002/// nor from the diagnostics produced when analysing the implicit expressions
2003/// required in a for-range statement.
2004void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2005 BeginEndFunction BEF) {
2006 CallExpr *CE = dyn_cast<CallExpr>(E);
2007 if (!CE)
2008 return;
2009 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2010 if (!D)
2011 return;
2012 SourceLocation Loc = D->getLocation();
2013
2014 std::string Description;
2015 bool IsTemplate = false;
2016 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2017 Description = SemaRef.getTemplateArgumentBindingsText(
2018 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2019 IsTemplate = true;
2020 }
2021
2022 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2023 << BEF << IsTemplate << Description << E->getType();
2024}
2025
2026/// Build a variable declaration for a for-range statement.
2027VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2028 QualType Type, StringRef Name) {
2029 DeclContext *DC = SemaRef.CurContext;
2030 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2031 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2032 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2033 TInfo, SC_None);
2034 Decl->setImplicit();
2035 return Decl;
2036}
2037
2038}
2039
2040static bool ObjCEnumerationCollection(Expr *Collection) {
2041 return !Collection->isTypeDependent()
2042 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2043}
2044
2045/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2046///
2047/// C++11 [stmt.ranged]:
2048/// A range-based for statement is equivalent to
2049///
2050/// {
2051/// auto && __range = range-init;
2052/// for ( auto __begin = begin-expr,
2053/// __end = end-expr;
2054/// __begin != __end;
2055/// ++__begin ) {
2056/// for-range-declaration = *__begin;
2057/// statement
2058/// }
2059/// }
2060///
2061/// The body of the loop is not available yet, since it cannot be analysed until
2062/// we have determined the type of the for-range-declaration.
2063StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2064 SourceLocation CoawaitLoc, Stmt *First,
2065 SourceLocation ColonLoc, Expr *Range,
2066 SourceLocation RParenLoc,
2067 BuildForRangeKind Kind) {
2068 if (!First)
2069 return StmtError();
2070
2071 if (Range && ObjCEnumerationCollection(Range))
2072 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2073
2074 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2075 assert(DS && "first part of for range not a decl stmt")(static_cast <bool> (DS && "first part of for range not a decl stmt"
) ? void (0) : __assert_fail ("DS && \"first part of for range not a decl stmt\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 2075, __extension__ __PRETTY_FUNCTION__))
;
2076
2077 if (!DS->isSingleDecl()) {
2078 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
2079 return StmtError();
2080 }
2081
2082 Decl *LoopVar = DS->getSingleDecl();
2083 if (LoopVar->isInvalidDecl() || !Range ||
2084 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2085 LoopVar->setInvalidDecl();
2086 return StmtError();
2087 }
2088
2089 // Build the coroutine state immediately and not later during template
2090 // instantiation
2091 if (!CoawaitLoc.isInvalid()) {
2092 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2093 return StmtError();
2094 }
2095
2096 // Build auto && __range = range-init
2097 // Divide by 2, since the variables are in the inner scope (loop body).
2098 const auto DepthStr = std::to_string(S->getDepth() / 2);
2099 SourceLocation RangeLoc = Range->getLocStart();
2100 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2101 Context.getAutoRRefDeductType(),
2102 std::string("__range") + DepthStr);
2103 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2104 diag::err_for_range_deduction_failure)) {
2105 LoopVar->setInvalidDecl();
2106 return StmtError();
2107 }
2108
2109 // Claim the type doesn't contain auto: we've already done the checking.
2110 DeclGroupPtrTy RangeGroup =
2111 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2112 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2113 if (RangeDecl.isInvalid()) {
2114 LoopVar->setInvalidDecl();
2115 return StmtError();
2116 }
2117
2118 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
2119 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2120 /*Cond=*/nullptr, /*Inc=*/nullptr,
2121 DS, RParenLoc, Kind);
2122}
2123
2124/// \brief Create the initialization, compare, and increment steps for
2125/// the range-based for loop expression.
2126/// This function does not handle array-based for loops,
2127/// which are created in Sema::BuildCXXForRangeStmt.
2128///
2129/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2130/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2131/// CandidateSet and BEF are set and some non-success value is returned on
2132/// failure.
2133static Sema::ForRangeStatus
2134BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2135 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2136 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2137 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2138 ExprResult *EndExpr, BeginEndFunction *BEF) {
2139 DeclarationNameInfo BeginNameInfo(
2140 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2141 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2142 ColonLoc);
2143
2144 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2145 Sema::LookupMemberName);
2146 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2147
2148 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2149 // - if _RangeT is a class type, the unqualified-ids begin and end are
2150 // looked up in the scope of class _RangeT as if by class member access
2151 // lookup (3.4.5), and if either (or both) finds at least one
2152 // declaration, begin-expr and end-expr are __range.begin() and
2153 // __range.end(), respectively;
2154 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2155 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2156
2157 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2158 SourceLocation RangeLoc = BeginVar->getLocation();
2159 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
2160
2161 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2162 << RangeLoc << BeginRange->getType() << *BEF;
2163 return Sema::FRS_DiagnosticIssued;
2164 }
2165 } else {
2166 // - otherwise, begin-expr and end-expr are begin(__range) and
2167 // end(__range), respectively, where begin and end are looked up with
2168 // argument-dependent lookup (3.4.2). For the purposes of this name
2169 // lookup, namespace std is an associated namespace.
2170
2171 }
2172
2173 *BEF = BEF_begin;
2174 Sema::ForRangeStatus RangeStatus =
2175 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2176 BeginMemberLookup, CandidateSet,
2177 BeginRange, BeginExpr);
2178
2179 if (RangeStatus != Sema::FRS_Success) {
2180 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2181 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2182 << ColonLoc << BEF_begin << BeginRange->getType();
2183 return RangeStatus;
2184 }
2185 if (!CoawaitLoc.isInvalid()) {
2186 // FIXME: getCurScope() should not be used during template instantiation.
2187 // We should pick up the set of unqualified lookup results for operator
2188 // co_await during the initial parse.
2189 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2190 BeginExpr->get());
2191 if (BeginExpr->isInvalid())
2192 return Sema::FRS_DiagnosticIssued;
2193 }
2194 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2195 diag::err_for_range_iter_deduction_failure)) {
2196 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2197 return Sema::FRS_DiagnosticIssued;
2198 }
2199
2200 *BEF = BEF_end;
2201 RangeStatus =
2202 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2203 EndMemberLookup, CandidateSet,
2204 EndRange, EndExpr);
2205 if (RangeStatus != Sema::FRS_Success) {
2206 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2207 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2208 << ColonLoc << BEF_end << EndRange->getType();
2209 return RangeStatus;
2210 }
2211 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2212 diag::err_for_range_iter_deduction_failure)) {
2213 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2214 return Sema::FRS_DiagnosticIssued;
2215 }
2216 return Sema::FRS_Success;
2217}
2218
2219/// Speculatively attempt to dereference an invalid range expression.
2220/// If the attempt fails, this function will return a valid, null StmtResult
2221/// and emit no diagnostics.
2222static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2223 SourceLocation ForLoc,
2224 SourceLocation CoawaitLoc,
2225 Stmt *LoopVarDecl,
2226 SourceLocation ColonLoc,
2227 Expr *Range,
2228 SourceLocation RangeLoc,
2229 SourceLocation RParenLoc) {
2230 // Determine whether we can rebuild the for-range statement with a
2231 // dereferenced range expression.
2232 ExprResult AdjustedRange;
2233 {
2234 Sema::SFINAETrap Trap(SemaRef);
2235
2236 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2237 if (AdjustedRange.isInvalid())
2238 return StmtResult();
2239
2240 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2241 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2242 RParenLoc, Sema::BFRK_Check);
2243 if (SR.isInvalid())
2244 return StmtResult();
2245 }
2246
2247 // The attempt to dereference worked well enough that it could produce a valid
2248 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2249 // case there are any other (non-fatal) problems with it.
2250 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2251 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2252 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2253 ColonLoc, AdjustedRange.get(), RParenLoc,
2254 Sema::BFRK_Rebuild);
2255}
2256
2257namespace {
2258/// RAII object to automatically invalidate a declaration if an error occurs.
2259struct InvalidateOnErrorScope {
2260 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2261 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2262 ~InvalidateOnErrorScope() {
2263 if (Enabled && Trap.hasErrorOccurred())
2264 D->setInvalidDecl();
2265 }
2266
2267 DiagnosticErrorTrap Trap;
2268 Decl *D;
2269 bool Enabled;
2270};
2271}
2272
2273/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2274StmtResult
2275Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2276 SourceLocation ColonLoc, Stmt *RangeDecl,
2277 Stmt *Begin, Stmt *End, Expr *Cond,
2278 Expr *Inc, Stmt *LoopVarDecl,
2279 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2280 // FIXME: This should not be used during template instantiation. We should
2281 // pick up the set of unqualified lookup results for the != and + operators
2282 // in the initial parse.
2283 //
2284 // Testcase (accepts-invalid):
2285 // template<typename T> void f() { for (auto x : T()) {} }
2286 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2287 // bool operator!=(N::X, N::X); void operator++(N::X);
2288 // void g() { f<N::X>(); }
2289 Scope *S = getCurScope();
2290
2291 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2292 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2293 QualType RangeVarType = RangeVar->getType();
2294
2295 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2296 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2297
2298 // If we hit any errors, mark the loop variable as invalid if its type
2299 // contains 'auto'.
2300 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2301 LoopVar->getType()->isUndeducedType());
2302
2303 StmtResult BeginDeclStmt = Begin;
2304 StmtResult EndDeclStmt = End;
2305 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2306
2307 if (RangeVarType->isDependentType()) {
2308 // The range is implicitly used as a placeholder when it is dependent.
2309 RangeVar->markUsed(Context);
2310
2311 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2312 // them in properly when we instantiate the loop.
2313 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2314 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2315 for (auto *Binding : DD->bindings())
2316 Binding->setType(Context.DependentTy);
2317 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2318 }
2319 } else if (!BeginDeclStmt.get()) {
2320 SourceLocation RangeLoc = RangeVar->getLocation();
2321
2322 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2323
2324 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2325 VK_LValue, ColonLoc);
2326 if (BeginRangeRef.isInvalid())
2327 return StmtError();
2328
2329 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2330 VK_LValue, ColonLoc);
2331 if (EndRangeRef.isInvalid())
2332 return StmtError();
2333
2334 QualType AutoType = Context.getAutoDeductType();
2335 Expr *Range = RangeVar->getInit();
2336 if (!Range)
2337 return StmtError();
2338 QualType RangeType = Range->getType();
2339
2340 if (RequireCompleteType(RangeLoc, RangeType,
2341 diag::err_for_range_incomplete_type))
2342 return StmtError();
2343
2344 // Build auto __begin = begin-expr, __end = end-expr.
2345 // Divide by 2, since the variables are in the inner scope (loop body).
2346 const auto DepthStr = std::to_string(S->getDepth() / 2);
2347 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2348 std::string("__begin") + DepthStr);
2349 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2350 std::string("__end") + DepthStr);
2351
2352 // Build begin-expr and end-expr and attach to __begin and __end variables.
2353 ExprResult BeginExpr, EndExpr;
2354 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2355 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2356 // __range + __bound, respectively, where __bound is the array bound. If
2357 // _RangeT is an array of unknown size or an array of incomplete type,
2358 // the program is ill-formed;
2359
2360 // begin-expr is __range.
2361 BeginExpr = BeginRangeRef;
2362 if (!CoawaitLoc.isInvalid()) {
2363 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2364 if (BeginExpr.isInvalid())
2365 return StmtError();
2366 }
2367 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2368 diag::err_for_range_iter_deduction_failure)) {
2369 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2370 return StmtError();
2371 }
2372
2373 // Find the array bound.
2374 ExprResult BoundExpr;
2375 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2376 BoundExpr = IntegerLiteral::Create(
2377 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2378 else if (const VariableArrayType *VAT =
2379 dyn_cast<VariableArrayType>(UnqAT)) {
2380 // For a variably modified type we can't just use the expression within
2381 // the array bounds, since we don't want that to be re-evaluated here.
2382 // Rather, we need to determine what it was when the array was first
2383 // created - so we resort to using sizeof(vla)/sizeof(element).
2384 // For e.g.
2385 // void f(int b) {
2386 // int vla[b];
2387 // b = -1; <-- This should not affect the num of iterations below
2388 // for (int &c : vla) { .. }
2389 // }
2390
2391 // FIXME: This results in codegen generating IR that recalculates the
2392 // run-time number of elements (as opposed to just using the IR Value
2393 // that corresponds to the run-time value of each bound that was
2394 // generated when the array was created.) If this proves too embarassing
2395 // even for unoptimized IR, consider passing a magic-value/cookie to
2396 // codegen that then knows to simply use that initial llvm::Value (that
2397 // corresponds to the bound at time of array creation) within
2398 // getelementptr. But be prepared to pay the price of increasing a
2399 // customized form of coupling between the two components - which could
2400 // be hard to maintain as the codebase evolves.
2401
2402 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2403 EndVar->getLocation(), UETT_SizeOf,
2404 /*isType=*/true,
2405 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2406 VAT->desugar(), RangeLoc))
2407 .getAsOpaquePtr(),
2408 EndVar->getSourceRange());
2409 if (SizeOfVLAExprR.isInvalid())
2410 return StmtError();
2411
2412 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2413 EndVar->getLocation(), UETT_SizeOf,
2414 /*isType=*/true,
2415 CreateParsedType(VAT->desugar(),
2416 Context.getTrivialTypeSourceInfo(
2417 VAT->getElementType(), RangeLoc))
2418 .getAsOpaquePtr(),
2419 EndVar->getSourceRange());
2420 if (SizeOfEachElementExprR.isInvalid())
2421 return StmtError();
2422
2423 BoundExpr =
2424 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2425 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2426 if (BoundExpr.isInvalid())
2427 return StmtError();
2428
2429 } else {
2430 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2431 // UnqAT is not incomplete and Range is not type-dependent.
2432 llvm_unreachable("Unexpected array type in for-range")::llvm::llvm_unreachable_internal("Unexpected array type in for-range"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 2432)
;
2433 }
2434
2435 // end-expr is __range + __bound.
2436 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2437 BoundExpr.get());
2438 if (EndExpr.isInvalid())
2439 return StmtError();
2440 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2441 diag::err_for_range_iter_deduction_failure)) {
2442 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2443 return StmtError();
2444 }
2445 } else {
2446 OverloadCandidateSet CandidateSet(RangeLoc,
2447 OverloadCandidateSet::CSK_Normal);
2448 BeginEndFunction BEFFailure;
2449 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2450 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2451 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2452 &BEFFailure);
2453
2454 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2455 BEFFailure == BEF_begin) {
2456 // If the range is being built from an array parameter, emit a
2457 // a diagnostic that it is being treated as a pointer.
2458 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2459 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2460 QualType ArrayTy = PVD->getOriginalType();
2461 QualType PointerTy = PVD->getType();
2462 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2463 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2464 << RangeLoc << PVD << ArrayTy << PointerTy;
2465 Diag(PVD->getLocation(), diag::note_declared_at);
2466 return StmtError();
2467 }
2468 }
2469 }
2470
2471 // If building the range failed, try dereferencing the range expression
2472 // unless a diagnostic was issued or the end function is problematic.
2473 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2474 CoawaitLoc,
2475 LoopVarDecl, ColonLoc,
2476 Range, RangeLoc,
2477 RParenLoc);
2478 if (SR.isInvalid() || SR.isUsable())
2479 return SR;
2480 }
2481
2482 // Otherwise, emit diagnostics if we haven't already.
2483 if (RangeStatus == FRS_NoViableFunction) {
2484 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2485 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2486 << RangeLoc << Range->getType() << BEFFailure;
2487 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2488 }
2489 // Return an error if no fix was discovered.
2490 if (RangeStatus != FRS_Success)
2491 return StmtError();
2492 }
2493
2494 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&(static_cast <bool> (!BeginExpr.isInvalid() && !
EndExpr.isInvalid() && "invalid range expression in for loop"
) ? void (0) : __assert_fail ("!BeginExpr.isInvalid() && !EndExpr.isInvalid() && \"invalid range expression in for loop\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 2495, __extension__ __PRETTY_FUNCTION__))
2495 "invalid range expression in for loop")(static_cast <bool> (!BeginExpr.isInvalid() && !
EndExpr.isInvalid() && "invalid range expression in for loop"
) ? void (0) : __assert_fail ("!BeginExpr.isInvalid() && !EndExpr.isInvalid() && \"invalid range expression in for loop\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 2495, __extension__ __PRETTY_FUNCTION__))
;
2496
2497 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2498 // C++1z removes this restriction.
2499 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2500 if (!Context.hasSameType(BeginType, EndType)) {
2501 Diag(RangeLoc, getLangOpts().CPlusPlus17
2502 ? diag::warn_for_range_begin_end_types_differ
2503 : diag::ext_for_range_begin_end_types_differ)
2504 << BeginType << EndType;
2505 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2506 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2507 }
2508
2509 BeginDeclStmt =
2510 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2511 EndDeclStmt =
2512 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2513
2514 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2515 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2516 VK_LValue, ColonLoc);
2517 if (BeginRef.isInvalid())
2518 return StmtError();
2519
2520 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2521 VK_LValue, ColonLoc);
2522 if (EndRef.isInvalid())
2523 return StmtError();
2524
2525 // Build and check __begin != __end expression.
2526 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2527 BeginRef.get(), EndRef.get());
2528 if (!NotEqExpr.isInvalid())
2529 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2530 if (!NotEqExpr.isInvalid())
2531 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2532 if (NotEqExpr.isInvalid()) {
2533 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2534 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2535 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2536 if (!Context.hasSameType(BeginType, EndType))
2537 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2538 return StmtError();
2539 }
2540
2541 // Build and check ++__begin expression.
2542 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2543 VK_LValue, ColonLoc);
2544 if (BeginRef.isInvalid())
2545 return StmtError();
2546
2547 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2548 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2549 // FIXME: getCurScope() should not be used during template instantiation.
2550 // We should pick up the set of unqualified lookup results for operator
2551 // co_await during the initial parse.
2552 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2553 if (!IncrExpr.isInvalid())
2554 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2555 if (IncrExpr.isInvalid()) {
2556 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2557 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2558 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2559 return StmtError();
2560 }
2561
2562 // Build and check *__begin expression.
2563 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2564 VK_LValue, ColonLoc);
2565 if (BeginRef.isInvalid())
2566 return StmtError();
2567
2568 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2569 if (DerefExpr.isInvalid()) {
2570 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2571 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2572 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2573 return StmtError();
2574 }
2575
2576 // Attach *__begin as initializer for VD. Don't touch it if we're just
2577 // trying to determine whether this would be a valid range.
2578 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2579 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2580 if (LoopVar->isInvalidDecl())
2581 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2582 }
2583 }
2584
2585 // Don't bother to actually allocate the result if we're just trying to
2586 // determine whether it would be valid.
2587 if (Kind == BFRK_Check)
2588 return StmtResult();
2589
2590 return new (Context) CXXForRangeStmt(
2591 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2592 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2593 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2594 ColonLoc, RParenLoc);
2595}
2596
2597/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2598/// statement.
2599StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2600 if (!S || !B)
2601 return StmtError();
2602 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2603
2604 ForStmt->setBody(B);
2605 return S;
2606}
2607
2608// Warn when the loop variable is a const reference that creates a copy.
2609// Suggest using the non-reference type for copies. If a copy can be prevented
2610// suggest the const reference type that would do so.
2611// For instance, given "for (const &Foo : Range)", suggest
2612// "for (const Foo : Range)" to denote a copy is made for the loop. If
2613// possible, also suggest "for (const &Bar : Range)" if this type prevents
2614// the copy altogether.
2615static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2616 const VarDecl *VD,
2617 QualType RangeInitType) {
2618 const Expr *InitExpr = VD->getInit();
2619 if (!InitExpr)
2620 return;
2621
2622 QualType VariableType = VD->getType();
2623
2624 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2625 if (!Cleanups->cleanupsHaveSideEffects())
2626 InitExpr = Cleanups->getSubExpr();
2627
2628 const MaterializeTemporaryExpr *MTE =
2629 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2630
2631 // No copy made.
2632 if (!MTE)
2633 return;
2634
2635 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2636
2637 // Searching for either UnaryOperator for dereference of a pointer or
2638 // CXXOperatorCallExpr for handling iterators.
2639 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2640 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2641 E = CCE->getArg(0);
2642 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2643 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2644 E = ME->getBase();
2645 } else {
2646 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2647 E = MTE->GetTemporaryExpr();
2648 }
2649 E = E->IgnoreImpCasts();
2650 }
2651
2652 bool ReturnsReference = false;
2653 if (isa<UnaryOperator>(E)) {
2654 ReturnsReference = true;
2655 } else {
2656 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2657 const FunctionDecl *FD = Call->getDirectCallee();
2658 QualType ReturnType = FD->getReturnType();
2659 ReturnsReference = ReturnType->isReferenceType();
2660 }
2661
2662 if (ReturnsReference) {
2663 // Loop variable creates a temporary. Suggest either to go with
2664 // non-reference loop variable to indiciate a copy is made, or
2665 // the correct time to bind a const reference.
2666 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2667 << VD << VariableType << E->getType();
2668 QualType NonReferenceType = VariableType.getNonReferenceType();
2669 NonReferenceType.removeLocalConst();
2670 QualType NewReferenceType =
2671 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2672 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2673 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2674 } else {
2675 // The range always returns a copy, so a temporary is always created.
2676 // Suggest removing the reference from the loop variable.
2677 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2678 << VD << RangeInitType;
2679 QualType NonReferenceType = VariableType.getNonReferenceType();
2680 NonReferenceType.removeLocalConst();
2681 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2682 << NonReferenceType << VD->getSourceRange();
2683 }
2684}
2685
2686// Warns when the loop variable can be changed to a reference type to
2687// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2688// "for (const Foo &x : Range)" if this form does not make a copy.
2689static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2690 const VarDecl *VD) {
2691 const Expr *InitExpr = VD->getInit();
2692 if (!InitExpr)
2693 return;
2694
2695 QualType VariableType = VD->getType();
2696
2697 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2698 if (!CE->getConstructor()->isCopyConstructor())
2699 return;
2700 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2701 if (CE->getCastKind() != CK_LValueToRValue)
2702 return;
2703 } else {
2704 return;
2705 }
2706
2707 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2708 // should be emitted. Also, only ignore POD types with trivial copy
2709 // constructors.
2710 if (VariableType.isPODType(SemaRef.Context))
2711 return;
2712
2713 // Suggest changing from a const variable to a const reference variable
2714 // if doing so will prevent a copy.
2715 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2716 << VD << VariableType << InitExpr->getType();
2717 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2718 << SemaRef.Context.getLValueReferenceType(VariableType)
2719 << VD->getSourceRange();
2720}
2721
2722/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2723/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2724/// using "const foo x" to show that a copy is made
2725/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2726/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2727/// prevent the copy.
2728/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2729/// Suggest "const foo &x" to prevent the copy.
2730static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2731 const CXXForRangeStmt *ForStmt) {
2732 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2733 ForStmt->getLocStart()) &&
2734 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2735 ForStmt->getLocStart()) &&
2736 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2737 ForStmt->getLocStart())) {
2738 return;
2739 }
2740
2741 const VarDecl *VD = ForStmt->getLoopVariable();
2742 if (!VD)
2743 return;
2744
2745 QualType VariableType = VD->getType();
2746
2747 if (VariableType->isIncompleteType())
2748 return;
2749
2750 const Expr *InitExpr = VD->getInit();
2751 if (!InitExpr)
2752 return;
2753
2754 if (VariableType->isReferenceType()) {
2755 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2756 ForStmt->getRangeInit()->getType());
2757 } else if (VariableType.isConstQualified()) {
2758 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2759 }
2760}
2761
2762/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2763/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2764/// body cannot be performed until after the type of the range variable is
2765/// determined.
2766StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2767 if (!S || !B)
2768 return StmtError();
2769
2770 if (isa<ObjCForCollectionStmt>(S))
2771 return FinishObjCForCollectionStmt(S, B);
2772
2773 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2774 ForStmt->setBody(B);
2775
2776 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2777 diag::warn_empty_range_based_for_body);
2778
2779 DiagnoseForRangeVariableCopies(*this, ForStmt);
2780
2781 return S;
2782}
2783
2784StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2785 SourceLocation LabelLoc,
2786 LabelDecl *TheDecl) {
2787 getCurFunction()->setHasBranchIntoScope();
2788 TheDecl->markUsed(Context);
2789 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2790}
2791
2792StmtResult
2793Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2794 Expr *E) {
2795 // Convert operand to void*
2796 if (!E->isTypeDependent()) {
2797 QualType ETy = E->getType();
2798 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2799 ExprResult ExprRes = E;
2800 AssignConvertType ConvTy =
2801 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2802 if (ExprRes.isInvalid())
2803 return StmtError();
2804 E = ExprRes.get();
2805 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2806 return StmtError();
2807 }
2808
2809 ExprResult ExprRes = ActOnFinishFullExpr(E);
2810 if (ExprRes.isInvalid())
2811 return StmtError();
2812 E = ExprRes.get();
2813
2814 getCurFunction()->setHasIndirectGoto();
2815
2816 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2817}
2818
2819static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2820 const Scope &DestScope) {
2821 if (!S.CurrentSEHFinally.empty() &&
2822 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2823 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2824 }
2825}
2826
2827StmtResult
2828Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2829 Scope *S = CurScope->getContinueParent();
2830 if (!S) {
2831 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2832 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2833 }
2834 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2835
2836 return new (Context) ContinueStmt(ContinueLoc);
2837}
2838
2839StmtResult
2840Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2841 Scope *S = CurScope->getBreakParent();
2842 if (!S) {
2843 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2844 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2845 }
2846 if (S->isOpenMPLoopScope())
2847 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2848 << "break");
2849 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2850
2851 return new (Context) BreakStmt(BreakLoc);
2852}
2853
2854/// \brief Determine whether the given expression is a candidate for
2855/// copy elision in either a return statement or a throw expression.
2856///
2857/// \param ReturnType If we're determining the copy elision candidate for
2858/// a return statement, this is the return type of the function. If we're
2859/// determining the copy elision candidate for a throw expression, this will
2860/// be a NULL type.
2861///
2862/// \param E The expression being returned from the function or block, or
2863/// being thrown.
2864///
2865/// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2866/// id-expressions that could be moved out of the function to be considered NRVO
2867/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2868/// determine whether we should try to move as part of a return or throw (which
2869/// does allow function parameters).
2870///
2871/// \returns The NRVO candidate variable, if the return statement may use the
2872/// NRVO, or NULL if there is no such candidate.
2873VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2874 bool AllowParamOrMoveConstructible) {
2875 if (!getLangOpts().CPlusPlus)
2876 return nullptr;
2877
2878 // - in a return statement in a function [where] ...
2879 // ... the expression is the name of a non-volatile automatic object ...
2880 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2881 if (!DR || DR->refersToEnclosingVariableOrCapture())
2882 return nullptr;
2883 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2884 if (!VD)
2885 return nullptr;
2886
2887 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
2888 return VD;
2889 return nullptr;
2890}
2891
2892bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2893 bool AllowParamOrMoveConstructible) {
2894 QualType VDType = VD->getType();
2895 // - in a return statement in a function with ...
2896 // ... a class return type ...
2897 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2898 if (!ReturnType->isRecordType())
2899 return false;
2900 // ... the same cv-unqualified type as the function return type ...
2901 // When considering moving this expression out, allow dissimilar types.
2902 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
2903 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2904 return false;
2905 }
2906
2907 // ...object (other than a function or catch-clause parameter)...
2908 if (VD->getKind() != Decl::Var &&
2909 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
2910 return false;
2911 if (VD->isExceptionVariable()) return false;
2912
2913 // ...automatic...
2914 if (!VD->hasLocalStorage()) return false;
2915
2916 // Return false if VD is a __block variable. We don't want to implicitly move
2917 // out of a __block variable during a return because we cannot assume the
2918 // variable will no longer be used.
2919 if (VD->hasAttr<BlocksAttr>()) return false;
2920
2921 if (AllowParamOrMoveConstructible)
2922 return true;
2923
2924 // ...non-volatile...
2925 if (VD->getType().isVolatileQualified()) return false;
2926
2927 // Variables with higher required alignment than their type's ABI
2928 // alignment cannot use NRVO.
2929 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2930 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2931 return false;
2932
2933 return true;
2934}
2935
2936/// \brief Perform the initialization of a potentially-movable value, which
2937/// is the result of return value.
2938///
2939/// This routine implements C++14 [class.copy]p32, which attempts to treat
2940/// returned lvalues as rvalues in certain cases (to prefer move construction),
2941/// then falls back to treating them as lvalues if that failed.
2942ExprResult
2943Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2944 const VarDecl *NRVOCandidate,
2945 QualType ResultType,
2946 Expr *Value,
2947 bool AllowNRVO) {
2948 // C++14 [class.copy]p32:
2949 // When the criteria for elision of a copy/move operation are met, but not for
2950 // an exception-declaration, and the object to be copied is designated by an
2951 // lvalue, or when the expression in a return statement is a (possibly
2952 // parenthesized) id-expression that names an object with automatic storage
2953 // duration declared in the body or parameter-declaration-clause of the
2954 // innermost enclosing function or lambda-expression, overload resolution to
2955 // select the constructor for the copy is first performed as if the object
2956 // were designated by an rvalue.
2957 ExprResult Res = ExprError();
2958
2959 if (AllowNRVO && !NRVOCandidate)
2960 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2961
2962 if (AllowNRVO && NRVOCandidate) {
2963 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2964 CK_NoOp, Value, VK_XValue);
2965
2966 Expr *InitExpr = &AsRvalue;
2967
2968 InitializationKind Kind = InitializationKind::CreateCopy(
2969 Value->getLocStart(), Value->getLocStart());
2970
2971 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2972 if (Seq) {
2973 for (const InitializationSequence::Step &Step : Seq.steps()) {
2974 if (!(Step.Kind ==
2975 InitializationSequence::SK_ConstructorInitialization ||
2976 (Step.Kind == InitializationSequence::SK_UserConversion &&
2977 isa<CXXConstructorDecl>(Step.Function.Function))))
2978 continue;
2979
2980 CXXConstructorDecl *Constructor =
2981 cast<CXXConstructorDecl>(Step.Function.Function);
2982
2983 const RValueReferenceType *RRefType
2984 = Constructor->getParamDecl(0)->getType()
2985 ->getAs<RValueReferenceType>();
2986
2987 // [...] If the first overload resolution fails or was not performed, or
2988 // if the type of the first parameter of the selected constructor is not
2989 // an rvalue reference to the object's type (possibly cv-qualified),
2990 // overload resolution is performed again, considering the object as an
2991 // lvalue.
2992 if (!RRefType ||
2993 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2994 NRVOCandidate->getType()))
2995 break;
2996
2997 // Promote "AsRvalue" to the heap, since we now need this
2998 // expression node to persist.
2999 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
3000 Value, nullptr, VK_XValue);
3001
3002 // Complete type-checking the initialization of the return type
3003 // using the constructor we found.
3004 Res = Seq.Perform(*this, Entity, Kind, Value);
3005 }
3006 }
3007 }
3008
3009 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3010 // above, or overload resolution failed. Either way, we need to try
3011 // (again) now with the return value expression as written.
3012 if (Res.isInvalid())
3013 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3014
3015 return Res;
3016}
3017
3018/// \brief Determine whether the declared return type of the specified function
3019/// contains 'auto'.
3020static bool hasDeducedReturnType(FunctionDecl *FD) {
3021 const FunctionProtoType *FPT =
3022 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3023 return FPT->getReturnType()->isUndeducedType();
3024}
3025
3026/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3027/// for capturing scopes.
3028///
3029StmtResult
3030Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3031 // If this is the first return we've seen, infer the return type.
3032 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3033 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3034 QualType FnRetType = CurCap->ReturnType;
3035 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3036 bool HasDeducedReturnType =
3037 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3038
3039 if (ExprEvalContexts.back().Context ==
3040 ExpressionEvaluationContext::DiscardedStatement &&
3041 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3042 if (RetValExp) {
3043 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3044 if (ER.isInvalid())
3045 return StmtError();
3046 RetValExp = ER.get();
3047 }
3048 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3049 }
3050
3051 if (HasDeducedReturnType) {
3052 // In C++1y, the return type may involve 'auto'.
3053 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3054 FunctionDecl *FD = CurLambda->CallOperator;
3055 if (CurCap->ReturnType.isNull())
3056 CurCap->ReturnType = FD->getReturnType();
3057
3058 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3059 assert(AT && "lost auto type from lambda return type")(static_cast <bool> (AT && "lost auto type from lambda return type"
) ? void (0) : __assert_fail ("AT && \"lost auto type from lambda return type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3059, __extension__ __PRETTY_FUNCTION__))
;
3060 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3061 FD->setInvalidDecl();
3062 return StmtError();
3063 }
3064 CurCap->ReturnType = FnRetType = FD->getReturnType();
3065 } else if (CurCap->HasImplicitReturnType) {
3066 // For blocks/lambdas with implicit return types, we check each return
3067 // statement individually, and deduce the common return type when the block
3068 // or lambda is completed.
3069 // FIXME: Fold this into the 'auto' codepath above.
3070 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3071 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3072 if (Result.isInvalid())
3073 return StmtError();
3074 RetValExp = Result.get();
3075
3076 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3077 // when deducing a return type for a lambda-expression (or by extension
3078 // for a block). These rules differ from the stated C++11 rules only in
3079 // that they remove top-level cv-qualifiers.
3080 if (!CurContext->isDependentContext())
3081 FnRetType = RetValExp->getType().getUnqualifiedType();
3082 else
3083 FnRetType = CurCap->ReturnType = Context.DependentTy;
3084 } else {
3085 if (RetValExp) {
3086 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3087 // initializer list, because it is not an expression (even
3088 // though we represent it as one). We still deduce 'void'.
3089 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3090 << RetValExp->getSourceRange();
3091 }
3092
3093 FnRetType = Context.VoidTy;
3094 }
3095
3096 // Although we'll properly infer the type of the block once it's completed,
3097 // make sure we provide a return type now for better error recovery.
3098 if (CurCap->ReturnType.isNull())
3099 CurCap->ReturnType = FnRetType;
3100 }
3101 assert(!FnRetType.isNull())(static_cast <bool> (!FnRetType.isNull()) ? void (0) : __assert_fail
("!FnRetType.isNull()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3101, __extension__ __PRETTY_FUNCTION__))
;
3102
3103 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3104 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3105 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3106 return StmtError();
3107 }
3108 } else if (CapturedRegionScopeInfo *CurRegion =
3109 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3110 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3111 return StmtError();
3112 } else {
3113 assert(CurLambda && "unknown kind of captured scope")(static_cast <bool> (CurLambda && "unknown kind of captured scope"
) ? void (0) : __assert_fail ("CurLambda && \"unknown kind of captured scope\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3113, __extension__ __PRETTY_FUNCTION__))
;
3114 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3115 ->getNoReturnAttr()) {
3116 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3117 return StmtError();
3118 }
3119 }
3120
3121 // Otherwise, verify that this result type matches the previous one. We are
3122 // pickier with blocks than for normal functions because we don't have GCC
3123 // compatibility to worry about here.
3124 const VarDecl *NRVOCandidate = nullptr;
3125 if (FnRetType->isDependentType()) {
3126 // Delay processing for now. TODO: there are lots of dependent
3127 // types we can conclusively prove aren't void.
3128 } else if (FnRetType->isVoidType()) {
3129 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3130 !(getLangOpts().CPlusPlus &&
3131 (RetValExp->isTypeDependent() ||
3132 RetValExp->getType()->isVoidType()))) {
3133 if (!getLangOpts().CPlusPlus &&
3134 RetValExp->getType()->isVoidType())
3135 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3136 else {
3137 Diag(ReturnLoc, diag::err_return_block_has_expr);
3138 RetValExp = nullptr;
3139 }
3140 }
3141 } else if (!RetValExp) {
3142 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3143 } else if (!RetValExp->isTypeDependent()) {
3144 // we have a non-void block with an expression, continue checking
3145
3146 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3147 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3148 // function return.
3149
3150 // In C++ the return statement is handled via a copy initialization.
3151 // the C version of which boils down to CheckSingleAssignmentConstraints.
3152 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3153 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3154 FnRetType,
3155 NRVOCandidate != nullptr);
3156 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3157 FnRetType, RetValExp);
3158 if (Res.isInvalid()) {
3159 // FIXME: Cleanup temporaries here, anyway?
3160 return StmtError();
3161 }
3162 RetValExp = Res.get();
3163 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3164 } else {
3165 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3166 }
3167
3168 if (RetValExp) {
3169 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3170 if (ER.isInvalid())
3171 return StmtError();
3172 RetValExp = ER.get();
3173 }
3174 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3175 NRVOCandidate);
3176
3177 // If we need to check for the named return value optimization,
3178 // or if we need to infer the return type,
3179 // save the return statement in our scope for later processing.
3180 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3181 FunctionScopes.back()->Returns.push_back(Result);
3182
3183 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3184 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3185
3186 return Result;
3187}
3188
3189namespace {
3190/// \brief Marks all typedefs in all local classes in a type referenced.
3191///
3192/// In a function like
3193/// auto f() {
3194/// struct S { typedef int a; };
3195/// return S();
3196/// }
3197///
3198/// the local type escapes and could be referenced in some TUs but not in
3199/// others. Pretend that all local typedefs are always referenced, to not warn
3200/// on this. This isn't necessary if f has internal linkage, or the typedef
3201/// is private.
3202class LocalTypedefNameReferencer
3203 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3204public:
3205 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3206 bool VisitRecordType(const RecordType *RT);
3207private:
3208 Sema &S;
3209};
3210bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3211 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3212 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3213 R->isDependentType())
3214 return true;
3215 for (auto *TmpD : R->decls())
3216 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3217 if (T->getAccess() != AS_private || R->hasFriends())
3218 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3219 return true;
3220}
3221}
3222
3223TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3224 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3225 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3226 TL = ATL.getModifiedLoc().IgnoreParens();
3227 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3228}
3229
3230/// Deduce the return type for a function from a returned expression, per
3231/// C++1y [dcl.spec.auto]p6.
3232bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3233 SourceLocation ReturnLoc,
3234 Expr *&RetExpr,
3235 AutoType *AT) {
3236 // If this is the conversion function for a lambda, we choose to deduce it
3237 // type from the corresponding call operator, not from the synthesized return
3238 // statement within it. See Sema::DeduceReturnType.
3239 if (isLambdaConversionOperator(FD))
3240 return false;
3241
3242 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3243 QualType Deduced;
3244
3245 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3246 // If the deduction is for a return statement and the initializer is
3247 // a braced-init-list, the program is ill-formed.
3248 Diag(RetExpr->getExprLoc(),
3249 getCurLambda() ? diag::err_lambda_return_init_list
3250 : diag::err_auto_fn_return_init_list)
3251 << RetExpr->getSourceRange();
3252 return true;
3253 }
3254
3255 if (FD->isDependentContext()) {
3256 // C++1y [dcl.spec.auto]p12:
3257 // Return type deduction [...] occurs when the definition is
3258 // instantiated even if the function body contains a return
3259 // statement with a non-type-dependent operand.
3260 assert(AT->isDeduced() && "should have deduced to dependent type")(static_cast <bool> (AT->isDeduced() && "should have deduced to dependent type"
) ? void (0) : __assert_fail ("AT->isDeduced() && \"should have deduced to dependent type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3260, __extension__ __PRETTY_FUNCTION__))
;
3261 return false;
3262 }
3263
3264 if (RetExpr) {
3265 // Otherwise, [...] deduce a value for U using the rules of template
3266 // argument deduction.
3267 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3268
3269 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3270 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3271 << OrigResultType.getType() << RetExpr->getType();
3272
3273 if (DAR != DAR_Succeeded)
3274 return true;
3275
3276 // If a local type is part of the returned type, mark its fields as
3277 // referenced.
3278 LocalTypedefNameReferencer Referencer(*this);
3279 Referencer.TraverseType(RetExpr->getType());
3280 } else {
3281 // In the case of a return with no operand, the initializer is considered
3282 // to be void().
3283 //
3284 // Deduction here can only succeed if the return type is exactly 'cv auto'
3285 // or 'decltype(auto)', so just check for that case directly.
3286 if (!OrigResultType.getType()->getAs<AutoType>()) {
3287 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3288 << OrigResultType.getType();
3289 return true;
3290 }
3291 // We always deduce U = void in this case.
3292 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3293 if (Deduced.isNull())
3294 return true;
3295 }
3296
3297 // If a function with a declared return type that contains a placeholder type
3298 // has multiple return statements, the return type is deduced for each return
3299 // statement. [...] if the type deduced is not the same in each deduction,
3300 // the program is ill-formed.
3301 QualType DeducedT = AT->getDeducedType();
3302 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3303 AutoType *NewAT = Deduced->getContainedAutoType();
3304 // It is possible that NewAT->getDeducedType() is null. When that happens,
3305 // we should not crash, instead we ignore this deduction.
3306 if (NewAT->getDeducedType().isNull())
3307 return false;
3308
3309 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3310 DeducedT);
3311 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3312 NewAT->getDeducedType());
3313 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3314 const LambdaScopeInfo *LambdaSI = getCurLambda();
3315 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3316 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3317 << NewAT->getDeducedType() << DeducedT
3318 << true /*IsLambda*/;
3319 } else {
3320 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3321 << (AT->isDecltypeAuto() ? 1 : 0)
3322 << NewAT->getDeducedType() << DeducedT;
3323 }
3324 return true;
3325 }
3326 } else if (!FD->isInvalidDecl()) {
3327 // Update all declarations of the function to have the deduced return type.
3328 Context.adjustDeducedFunctionResultType(FD, Deduced);
3329 }
3330
3331 return false;
3332}
3333
3334StmtResult
3335Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3336 Scope *CurScope) {
3337 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3338 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3339 ExpressionEvaluationContext::DiscardedStatement)
3340 return R;
3341
3342 if (VarDecl *VD =
3343 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3344 CurScope->addNRVOCandidate(VD);
3345 } else {
3346 CurScope->setNoNRVO();
3347 }
3348
3349 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3350
3351 return R;
3352}
3353
3354StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3355 // Check for unexpanded parameter packs.
3356 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3357 return StmtError();
3358
3359 if (isa<CapturingScopeInfo>(getCurFunction()))
3360 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3361
3362 QualType FnRetType;
3363 QualType RelatedRetType;
3364 const AttrVec *Attrs = nullptr;
3365 bool isObjCMethod = false;
3366
3367 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3368 FnRetType = FD->getReturnType();
3369 if (FD->hasAttrs())
3370 Attrs = &FD->getAttrs();
3371 if (FD->isNoReturn())
3372 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3373 << FD->getDeclName();
3374 if (FD->isMain() && RetValExp)
3375 if (isa<CXXBoolLiteralExpr>(RetValExp))
3376 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3377 << RetValExp->getSourceRange();
3378 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3379 FnRetType = MD->getReturnType();
3380 isObjCMethod = true;
3381 if (MD->hasAttrs())
3382 Attrs = &MD->getAttrs();
3383 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3384 // In the implementation of a method with a related return type, the
3385 // type used to type-check the validity of return statements within the
3386 // method body is a pointer to the type of the class being implemented.
3387 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3388 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3389 }
3390 } else // If we don't have a function/method context, bail.
3391 return StmtError();
3392
3393 // C++1z: discarded return statements are not considered when deducing a
3394 // return type.
3395 if (ExprEvalContexts.back().Context ==
3396 ExpressionEvaluationContext::DiscardedStatement &&
3397 FnRetType->getContainedAutoType()) {
3398 if (RetValExp) {
3399 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3400 if (ER.isInvalid())
3401 return StmtError();
3402 RetValExp = ER.get();
3403 }
3404 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3405 }
3406
3407 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3408 // deduction.
3409 if (getLangOpts().CPlusPlus14) {
3410 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3411 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3412 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3413 FD->setInvalidDecl();
3414 return StmtError();
3415 } else {
3416 FnRetType = FD->getReturnType();
3417 }
3418 }
3419 }
3420
3421 bool HasDependentReturnType = FnRetType->isDependentType();
3422
3423 ReturnStmt *Result = nullptr;
3424 if (FnRetType->isVoidType()) {
3425 if (RetValExp) {
3426 if (isa<InitListExpr>(RetValExp)) {
3427 // We simply never allow init lists as the return value of void
3428 // functions. This is compatible because this was never allowed before,
3429 // so there's no legacy code to deal with.
3430 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3431 int FunctionKind = 0;
3432 if (isa<ObjCMethodDecl>(CurDecl))
3433 FunctionKind = 1;
3434 else if (isa<CXXConstructorDecl>(CurDecl))
3435 FunctionKind = 2;
3436 else if (isa<CXXDestructorDecl>(CurDecl))
3437 FunctionKind = 3;
3438
3439 Diag(ReturnLoc, diag::err_return_init_list)
3440 << CurDecl->getDeclName() << FunctionKind
3441 << RetValExp->getSourceRange();
3442
3443 // Drop the expression.
3444 RetValExp = nullptr;
3445 } else if (!RetValExp->isTypeDependent()) {
3446 // C99 6.8.6.4p1 (ext_ since GCC warns)
3447 unsigned D = diag::ext_return_has_expr;
3448 if (RetValExp->getType()->isVoidType()) {
3449 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3450 if (isa<CXXConstructorDecl>(CurDecl) ||
3451 isa<CXXDestructorDecl>(CurDecl))
3452 D = diag::err_ctor_dtor_returns_void;
3453 else
3454 D = diag::ext_return_has_void_expr;
3455 }
3456 else {
3457 ExprResult Result = RetValExp;
3458 Result = IgnoredValueConversions(Result.get());
3459 if (Result.isInvalid())
3460 return StmtError();
3461 RetValExp = Result.get();
3462 RetValExp = ImpCastExprToType(RetValExp,
3463 Context.VoidTy, CK_ToVoid).get();
3464 }
3465 // return of void in constructor/destructor is illegal in C++.
3466 if (D == diag::err_ctor_dtor_returns_void) {
3467 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3468 Diag(ReturnLoc, D)
3469 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3470 << RetValExp->getSourceRange();
3471 }
3472 // return (some void expression); is legal in C++.
3473 else if (D != diag::ext_return_has_void_expr ||
3474 !getLangOpts().CPlusPlus) {
3475 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3476
3477 int FunctionKind = 0;
3478 if (isa<ObjCMethodDecl>(CurDecl))
3479 FunctionKind = 1;
3480 else if (isa<CXXConstructorDecl>(CurDecl))
3481 FunctionKind = 2;
3482 else if (isa<CXXDestructorDecl>(CurDecl))
3483 FunctionKind = 3;
3484
3485 Diag(ReturnLoc, D)
3486 << CurDecl->getDeclName() << FunctionKind
3487 << RetValExp->getSourceRange();
3488 }
3489 }
3490
3491 if (RetValExp) {
3492 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3493 if (ER.isInvalid())
3494 return StmtError();
3495 RetValExp = ER.get();
3496 }
3497 }
3498
3499 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3500 } else if (!RetValExp && !HasDependentReturnType) {
3501 FunctionDecl *FD = getCurFunctionDecl();
3502
3503 unsigned DiagID;
3504 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3505 // C++11 [stmt.return]p2
3506 DiagID = diag::err_constexpr_return_missing_expr;
3507 FD->setInvalidDecl();
3508 } else if (getLangOpts().C99) {
3509 // C99 6.8.6.4p1 (ext_ since GCC warns)
3510 DiagID = diag::ext_return_missing_expr;
3511 } else {
3512 // C90 6.6.6.4p4
3513 DiagID = diag::warn_return_missing_expr;
3514 }
3515
3516 if (FD)
3517 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3518 else
3519 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3520
3521 Result = new (Context) ReturnStmt(ReturnLoc);
3522 } else {
3523 assert(RetValExp || HasDependentReturnType)(static_cast <bool> (RetValExp || HasDependentReturnType
) ? void (0) : __assert_fail ("RetValExp || HasDependentReturnType"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3523, __extension__ __PRETTY_FUNCTION__))
;
3524 const VarDecl *NRVOCandidate = nullptr;
3525
3526 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3527
3528 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3529 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3530 // function return.
3531
3532 // In C++ the return statement is handled via a copy initialization,
3533 // the C version of which boils down to CheckSingleAssignmentConstraints.
3534 if (RetValExp)
3535 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3536 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3537 // we have a non-void function with an expression, continue checking
3538 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3539 RetType,
3540 NRVOCandidate != nullptr);
3541 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3542 RetType, RetValExp);
3543 if (Res.isInvalid()) {
3544 // FIXME: Clean up temporaries here anyway?
3545 return StmtError();
3546 }
3547 RetValExp = Res.getAs<Expr>();
3548
3549 // If we have a related result type, we need to implicitly
3550 // convert back to the formal result type. We can't pretend to
3551 // initialize the result again --- we might end double-retaining
3552 // --- so instead we initialize a notional temporary.
3553 if (!RelatedRetType.isNull()) {
3554 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3555 FnRetType);
3556 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3557 if (Res.isInvalid()) {
3558 // FIXME: Clean up temporaries here anyway?
3559 return StmtError();
3560 }
3561 RetValExp = Res.getAs<Expr>();
3562 }
3563
3564 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3565 getCurFunctionDecl());
3566 }
3567
3568 if (RetValExp) {
3569 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3570 if (ER.isInvalid())
3571 return StmtError();
3572 RetValExp = ER.get();
3573 }
3574 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3575 }
3576
3577 // If we need to check for the named return value optimization, save the
3578 // return statement in our scope for later processing.
3579 if (Result->getNRVOCandidate())
3580 FunctionScopes.back()->Returns.push_back(Result);
3581
3582 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3583 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3584
3585 return Result;
3586}
3587
3588StmtResult
3589Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3590 SourceLocation RParen, Decl *Parm,
3591 Stmt *Body) {
3592 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3593 if (Var && Var->isInvalidDecl())
3594 return StmtError();
3595
3596 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3597}
3598
3599StmtResult
3600Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3601 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3602}
3603
3604StmtResult
3605Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3606 MultiStmtArg CatchStmts, Stmt *Finally) {
3607 if (!getLangOpts().ObjCExceptions)
3608 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3609
3610 getCurFunction()->setHasBranchProtectedScope();
3611 unsigned NumCatchStmts = CatchStmts.size();
3612 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3613 NumCatchStmts, Finally);
3614}
3615
3616StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3617 if (Throw) {
3618 ExprResult Result = DefaultLvalueConversion(Throw);
3619 if (Result.isInvalid())
3620 return StmtError();
3621
3622 Result = ActOnFinishFullExpr(Result.get());
3623 if (Result.isInvalid())
3624 return StmtError();
3625 Throw = Result.get();
3626
3627 QualType ThrowType = Throw->getType();
3628 // Make sure the expression type is an ObjC pointer or "void *".
3629 if (!ThrowType->isDependentType() &&
3630 !ThrowType->isObjCObjectPointerType()) {
3631 const PointerType *PT = ThrowType->getAs<PointerType>();
3632 if (!PT || !PT->getPointeeType()->isVoidType())
3633 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3634 << Throw->getType() << Throw->getSourceRange());
3635 }
3636 }
3637
3638 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3639}
3640
3641StmtResult
3642Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3643 Scope *CurScope) {
3644 if (!getLangOpts().ObjCExceptions)
3645 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3646
3647 if (!Throw) {
3648 // @throw without an expression designates a rethrow (which must occur
3649 // in the context of an @catch clause).
3650 Scope *AtCatchParent = CurScope;
3651 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3652 AtCatchParent = AtCatchParent->getParent();
3653 if (!AtCatchParent)
3654 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3655 }
3656 return BuildObjCAtThrowStmt(AtLoc, Throw);
3657}
3658
3659ExprResult
3660Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3661 ExprResult result = DefaultLvalueConversion(operand);
3662 if (result.isInvalid())
3663 return ExprError();
3664 operand = result.get();
3665
3666 // Make sure the expression type is an ObjC pointer or "void *".
3667 QualType type = operand->getType();
3668 if (!type->isDependentType() &&
3669 !type->isObjCObjectPointerType()) {
3670 const PointerType *pointerType = type->getAs<PointerType>();
3671 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3672 if (getLangOpts().CPlusPlus) {
3673 if (RequireCompleteType(atLoc, type,
3674 diag::err_incomplete_receiver_type))
3675 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3676 << type << operand->getSourceRange();
3677
3678 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3679 if (result.isInvalid())
3680 return ExprError();
3681 if (!result.isUsable())
3682 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3683 << type << operand->getSourceRange();
3684
3685 operand = result.get();
3686 } else {
3687 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3688 << type << operand->getSourceRange();
3689 }
3690 }
3691 }
3692
3693 // The operand to @synchronized is a full-expression.
3694 return ActOnFinishFullExpr(operand);
3695}
3696
3697StmtResult
3698Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3699 Stmt *SyncBody) {
3700 // We can't jump into or indirect-jump out of a @synchronized block.
3701 getCurFunction()->setHasBranchProtectedScope();
3702 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3703}
3704
3705/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3706/// and creates a proper catch handler from them.
3707StmtResult
3708Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3709 Stmt *HandlerBlock) {
3710 // There's nothing to test that ActOnExceptionDecl didn't already test.
3711 return new (Context)
3712 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3713}
3714
3715StmtResult
3716Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3717 getCurFunction()->setHasBranchProtectedScope();
3718 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3719}
3720
3721namespace {
3722class CatchHandlerType {
3723 QualType QT;
3724 unsigned IsPointer : 1;
3725
3726 // This is a special constructor to be used only with DenseMapInfo's
3727 // getEmptyKey() and getTombstoneKey() functions.
3728 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3729 enum Unique { ForDenseMap };
3730 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3731
3732public:
3733 /// Used when creating a CatchHandlerType from a handler type; will determine
3734 /// whether the type is a pointer or reference and will strip off the top
3735 /// level pointer and cv-qualifiers.
3736 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3737 if (QT->isPointerType())
3738 IsPointer = true;
3739
3740 if (IsPointer || QT->isReferenceType())
3741 QT = QT->getPointeeType();
3742 QT = QT.getUnqualifiedType();
3743 }
3744
3745 /// Used when creating a CatchHandlerType from a base class type; pretends the
3746 /// type passed in had the pointer qualifier, does not need to get an
3747 /// unqualified type.
3748 CatchHandlerType(QualType QT, bool IsPointer)
3749 : QT(QT), IsPointer(IsPointer) {}
3750
3751 QualType underlying() const { return QT; }
3752 bool isPointer() const { return IsPointer; }
3753
3754 friend bool operator==(const CatchHandlerType &LHS,
3755 const CatchHandlerType &RHS) {
3756 // If the pointer qualification does not match, we can return early.
3757 if (LHS.IsPointer != RHS.IsPointer)
3758 return false;
3759 // Otherwise, check the underlying type without cv-qualifiers.
3760 return LHS.QT == RHS.QT;
3761 }
3762};
3763} // namespace
3764
3765namespace llvm {
3766template <> struct DenseMapInfo<CatchHandlerType> {
3767 static CatchHandlerType getEmptyKey() {
3768 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3769 CatchHandlerType::ForDenseMap);
3770 }
3771
3772 static CatchHandlerType getTombstoneKey() {
3773 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3774 CatchHandlerType::ForDenseMap);
3775 }
3776
3777 static unsigned getHashValue(const CatchHandlerType &Base) {
3778 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3779 }
3780
3781 static bool isEqual(const CatchHandlerType &LHS,
3782 const CatchHandlerType &RHS) {
3783 return LHS == RHS;
3784 }
3785};
3786}
3787
3788namespace {
3789class CatchTypePublicBases {
3790 ASTContext &Ctx;
3791 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3792 const bool CheckAgainstPointer;
3793
3794 CXXCatchStmt *FoundHandler;
3795 CanQualType FoundHandlerType;
3796
3797public:
3798 CatchTypePublicBases(
3799 ASTContext &Ctx,
3800 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3801 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3802 FoundHandler(nullptr) {}
3803
3804 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3805 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3806
3807 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3808 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3809 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3810 const auto &M = TypesToCheck;
3811 auto I = M.find(Check);
3812 if (I != M.end()) {
3813 FoundHandler = I->second;
3814 FoundHandlerType = Ctx.getCanonicalType(S->getType());
3815 return true;
3816 }
3817 }
3818 return false;
3819 }
3820};
3821}
3822
3823/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3824/// handlers and creates a try statement from them.
3825StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3826 ArrayRef<Stmt *> Handlers) {
3827 // Don't report an error if 'try' is used in system headers.
3828 if (!getLangOpts().CXXExceptions &&
1
Assuming the condition is false
3829 !getSourceManager().isInSystemHeader(TryLoc))
3830 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3831
3832 // Exceptions aren't allowed in CUDA device code.
3833 if (getLangOpts().CUDA)
2
Assuming the condition is true
3
Taking true branch
3834 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4
Calling 'operator<<'
21
Returned allocated memory
3835 << "try" << CurrentCUDATarget();
3836
3837 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
22
Potential leak of memory pointed to by field 'DiagStorage'
3838 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3839
3840 sema::FunctionScopeInfo *FSI = getCurFunction();
3841
3842 // C++ try is incompatible with SEH __try.
3843 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
3844 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3845 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
3846 }
3847
3848 const unsigned NumHandlers = Handlers.size();
3849 assert(!Handlers.empty() &&(static_cast <bool> (!Handlers.empty() && "The parser shouldn't call this if there are no handlers."
) ? void (0) : __assert_fail ("!Handlers.empty() && \"The parser shouldn't call this if there are no handlers.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3850, __extension__ __PRETTY_FUNCTION__))
3850 "The parser shouldn't call this if there are no handlers.")(static_cast <bool> (!Handlers.empty() && "The parser shouldn't call this if there are no handlers."
) ? void (0) : __assert_fail ("!Handlers.empty() && \"The parser shouldn't call this if there are no handlers.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3850, __extension__ __PRETTY_FUNCTION__))
;
3851
3852 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
3853 for (unsigned i = 0; i < NumHandlers; ++i) {
3854 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
3855
3856 // Diagnose when the handler is a catch-all handler, but it isn't the last
3857 // handler for the try block. [except.handle]p5. Also, skip exception
3858 // declarations that are invalid, since we can't usefully report on them.
3859 if (!H->getExceptionDecl()) {
3860 if (i < NumHandlers - 1)
3861 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
3862 continue;
3863 } else if (H->getExceptionDecl()->isInvalidDecl())
3864 continue;
3865
3866 // Walk the type hierarchy to diagnose when this type has already been
3867 // handled (duplication), or cannot be handled (derivation inversion). We
3868 // ignore top-level cv-qualifiers, per [except.handle]p3
3869 CatchHandlerType HandlerCHT =
3870 (QualType)Context.getCanonicalType(H->getCaughtType());
3871
3872 // We can ignore whether the type is a reference or a pointer; we need the
3873 // underlying declaration type in order to get at the underlying record
3874 // decl, if there is one.
3875 QualType Underlying = HandlerCHT.underlying();
3876 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3877 if (!RD->hasDefinition())
3878 continue;
3879 // Check that none of the public, unambiguous base classes are in the
3880 // map ([except.handle]p1). Give the base classes the same pointer
3881 // qualification as the original type we are basing off of. This allows
3882 // comparison against the handler type using the same top-level pointer
3883 // as the original type.
3884 CXXBasePaths Paths;
3885 Paths.setOrigin(RD);
3886 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3887 if (RD->lookupInBases(CTPB, Paths)) {
3888 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3889 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3890 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3891 diag::warn_exception_caught_by_earlier_handler)
3892 << H->getCaughtType();
3893 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3894 diag::note_previous_exception_handler)
3895 << Problem->getCaughtType();
3896 }
3897 }
3898 }
3899
3900 // Add the type the list of ones we have handled; diagnose if we've already
3901 // handled it.
3902 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3903 if (!R.second) {
3904 const CXXCatchStmt *Problem = R.first->second;
3905 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3906 diag::warn_exception_caught_by_earlier_handler)
3907 << H->getCaughtType();
3908 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3909 diag::note_previous_exception_handler)
3910 << Problem->getCaughtType();
3911 }
3912 }
3913
3914 FSI->setHasCXXTry(TryLoc);
3915
3916 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3917}
3918
3919StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3920 Stmt *TryBlock, Stmt *Handler) {
3921 assert(TryBlock && Handler)(static_cast <bool> (TryBlock && Handler) ? void
(0) : __assert_fail ("TryBlock && Handler", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3921, __extension__ __PRETTY_FUNCTION__))
;
3922
3923 sema::FunctionScopeInfo *FSI = getCurFunction();
3924
3925 // SEH __try is incompatible with C++ try. Borland appears to support this,
3926 // however.
3927 if (!getLangOpts().Borland) {
3928 if (FSI->FirstCXXTryLoc.isValid()) {
3929 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3930 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3931 }
3932 }
3933
3934 FSI->setHasSEHTry(TryLoc);
3935
3936 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3937 // track if they use SEH.
3938 DeclContext *DC = CurContext;
3939 while (DC && !DC->isFunctionOrMethod())
3940 DC = DC->getParent();
3941 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3942 if (FD)
3943 FD->setUsesSEHTry(true);
3944 else
3945 Diag(TryLoc, diag::err_seh_try_outside_functions);
3946
3947 // Reject __try on unsupported targets.
3948 if (!Context.getTargetInfo().isSEHTrySupported())
3949 Diag(TryLoc, diag::err_seh_try_unsupported);
3950
3951 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
3952}
3953
3954StmtResult
3955Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3956 Expr *FilterExpr,
3957 Stmt *Block) {
3958 assert(FilterExpr && Block)(static_cast <bool> (FilterExpr && Block) ? void
(0) : __assert_fail ("FilterExpr && Block", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3958, __extension__ __PRETTY_FUNCTION__))
;
3959
3960 if(!FilterExpr->getType()->isIntegerType()) {
3961 return StmtError(Diag(FilterExpr->getExprLoc(),
3962 diag::err_filter_expression_integral)
3963 << FilterExpr->getType());
3964 }
3965
3966 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3967}
3968
3969void Sema::ActOnStartSEHFinallyBlock() {
3970 CurrentSEHFinally.push_back(CurScope);
3971}
3972
3973void Sema::ActOnAbortSEHFinallyBlock() {
3974 CurrentSEHFinally.pop_back();
3975}
3976
3977StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
3978 assert(Block)(static_cast <bool> (Block) ? void (0) : __assert_fail (
"Block", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 3978, __extension__ __PRETTY_FUNCTION__))
;
3979 CurrentSEHFinally.pop_back();
3980 return SEHFinallyStmt::Create(Context, Loc, Block);
3981}
3982
3983StmtResult
3984Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3985 Scope *SEHTryParent = CurScope;
3986 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3987 SEHTryParent = SEHTryParent->getParent();
3988 if (!SEHTryParent)
3989 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3990 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
3991
3992 return new (Context) SEHLeaveStmt(Loc);
3993}
3994
3995StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3996 bool IsIfExists,
3997 NestedNameSpecifierLoc QualifierLoc,
3998 DeclarationNameInfo NameInfo,
3999 Stmt *Nested)
4000{
4001 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4002 QualifierLoc, NameInfo,
4003 cast<CompoundStmt>(Nested));
4004}
4005
4006
4007StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4008 bool IsIfExists,
4009 CXXScopeSpec &SS,
4010 UnqualifiedId &Name,
4011 Stmt *Nested) {
4012 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4013 SS.getWithLocInContext(Context),
4014 GetNameFromUnqualifiedId(Name),
4015 Nested);
4016}
4017
4018RecordDecl*
4019Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4020 unsigned NumParams) {
4021 DeclContext *DC = CurContext;
4022 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4023 DC = DC->getParent();
4024
4025 RecordDecl *RD = nullptr;
4026 if (getLangOpts().CPlusPlus)
4027 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4028 /*Id=*/nullptr);
4029 else
4030 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4031
4032 RD->setCapturedRecord();
4033 DC->addDecl(RD);
4034 RD->setImplicit();
4035 RD->startDefinition();
4036
4037 assert(NumParams > 0 && "CapturedStmt requires context parameter")(static_cast <bool> (NumParams > 0 && "CapturedStmt requires context parameter"
) ? void (0) : __assert_fail ("NumParams > 0 && \"CapturedStmt requires context parameter\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 4037, __extension__ __PRETTY_FUNCTION__))
;
4038 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4039 DC->addDecl(CD);
4040 return RD;
4041}
4042
4043static void buildCapturedStmtCaptureList(
4044 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4045 SmallVectorImpl<Expr *> &CaptureInits,
4046 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
4047
4048 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
4049 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
4050
4051 if (Cap->isThisCapture()) {
4052 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
4053 CapturedStmt::VCK_This));
4054 CaptureInits.push_back(Cap->getInitExpr());
4055 continue;
4056 } else if (Cap->isVLATypeCapture()) {
4057 Captures.push_back(
4058 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
4059 CaptureInits.push_back(nullptr);
4060 continue;
4061 }
4062
4063 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
4064 Cap->isReferenceCapture()
4065 ? CapturedStmt::VCK_ByRef
4066 : CapturedStmt::VCK_ByCopy,
4067 Cap->getVariable()));
4068 CaptureInits.push_back(Cap->getInitExpr());
4069 }
4070}
4071
4072void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4073 CapturedRegionKind Kind,
4074 unsigned NumParams) {
4075 CapturedDecl *CD = nullptr;
4076 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4077
4078 // Build the context parameter
4079 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4080 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4081 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4082 auto *Param =
4083 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4084 ImplicitParamDecl::CapturedContext);
4085 DC->addDecl(Param);
4086
4087 CD->setContextParam(0, Param);
4088
4089 // Enter the capturing scope for this captured region.
4090 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4091
4092 if (CurScope)
4093 PushDeclContext(CurScope, CD);
4094 else
4095 CurContext = CD;
4096
4097 PushExpressionEvaluationContext(
4098 ExpressionEvaluationContext::PotentiallyEvaluated);
4099}
4100
4101void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4102 CapturedRegionKind Kind,
4103 ArrayRef<CapturedParamNameType> Params) {
4104 CapturedDecl *CD = nullptr;
4105 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4106
4107 // Build the context parameter
4108 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4109 bool ContextIsFound = false;
4110 unsigned ParamNum = 0;
4111 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4112 E = Params.end();
4113 I != E; ++I, ++ParamNum) {
4114 if (I->second.isNull()) {
4115 assert(!ContextIsFound &&(static_cast <bool> (!ContextIsFound && "null type has been found already for '__context' parameter"
) ? void (0) : __assert_fail ("!ContextIsFound && \"null type has been found already for '__context' parameter\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 4116, __extension__ __PRETTY_FUNCTION__))
4116 "null type has been found already for '__context' parameter")(static_cast <bool> (!ContextIsFound && "null type has been found already for '__context' parameter"
) ? void (0) : __assert_fail ("!ContextIsFound && \"null type has been found already for '__context' parameter\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 4116, __extension__ __PRETTY_FUNCTION__))
;
4117 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4118 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4119 auto *Param =
4120 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4121 ImplicitParamDecl::CapturedContext);
4122 DC->addDecl(Param);
4123 CD->setContextParam(ParamNum, Param);
4124 ContextIsFound = true;
4125 } else {
4126 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4127 auto *Param =
4128 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4129 ImplicitParamDecl::CapturedContext);
4130 DC->addDecl(Param);
4131 CD->setParam(ParamNum, Param);
4132 }
4133 }
4134 assert(ContextIsFound && "no null type for '__context' parameter")(static_cast <bool> (ContextIsFound && "no null type for '__context' parameter"
) ? void (0) : __assert_fail ("ContextIsFound && \"no null type for '__context' parameter\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaStmt.cpp"
, 4134, __extension__ __PRETTY_FUNCTION__))
;
4135 if (!ContextIsFound) {
4136 // Add __context implicitly if it is not specified.
4137 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4138 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4139 auto *Param =
4140 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4141 ImplicitParamDecl::CapturedContext);
4142 DC->addDecl(Param);
4143 CD->setContextParam(ParamNum, Param);
4144 }
4145 // Enter the capturing scope for this captured region.
4146 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4147
4148 if (CurScope)
4149 PushDeclContext(CurScope, CD);
4150 else
4151 CurContext = CD;
4152
4153 PushExpressionEvaluationContext(
4154 ExpressionEvaluationContext::PotentiallyEvaluated);
4155}
4156
4157void Sema::ActOnCapturedRegionError() {
4158 DiscardCleanupsInEvaluationContext();
4159 PopExpressionEvaluationContext();
4160
4161 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4162 RecordDecl *Record = RSI->TheRecordDecl;
4163 Record->setInvalidDecl();
4164
4165 SmallVector<Decl*, 4> Fields(Record->fields());
4166 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4167 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
4168
4169 PopDeclContext();
4170 PopFunctionScopeInfo();
4171}
4172
4173StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4174 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4175
4176 SmallVector<CapturedStmt::Capture, 4> Captures;
4177 SmallVector<Expr *, 4> CaptureInits;
4178 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4179
4180 CapturedDecl *CD = RSI->TheCapturedDecl;
4181 RecordDecl *RD = RSI->TheRecordDecl;
4182
4183 CapturedStmt *Res = CapturedStmt::Create(
4184 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4185 Captures, CaptureInits, CD, RD);
4186
4187 CD->setBody(Res->getCapturedStmt());
4188 RD->completeDefinition();
4189
4190 DiscardCleanupsInEvaluationContext();
4191 PopExpressionEvaluationContext();
4192
4193 PopDeclContext();
4194 PopFunctionScopeInfo();
4195
4196 return Res;
4197}

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
18#include "clang/AST/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/LocInfoType.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NSAPI.h"
28#include "clang/AST/PrettyPrinter.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/TypeOrdering.h"
32#include "clang/Basic/ExpressionTraits.h"
33#include "clang/Basic/LangOptions.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/ScopeInfo.h"
49#include "clang/Sema/TypoCorrection.h"
50#include "clang/Sema/Weak.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/SetVector.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
62namespace 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
70namespace clang {
71 class ADLResult;
72 class ASTConsumer;
73 class ASTContext;
74 class ASTMutationListener;
75 class ASTReader;
76 class ASTWriter;
77 class ArrayType;
78 class AttributeList;
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 OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
157 class OMPClause;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
160 class OverloadExpr;
161 class ParenListExpr;
162 class ParmVarDecl;
163 class Preprocessor;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
166 class QualType;
167 class StandardConversionSequence;
168 class Stmt;
169 class StringLiteral;
170 class SwitchStmt;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
174 class TemplateDecl;
175 class TemplateInstantiationCallback;
176 class TemplateParameterList;
177 class TemplatePartialOrderingContext;
178 class TemplateTemplateParmDecl;
179 class Token;
180 class TypeAliasDecl;
181 class TypedefDecl;
182 class TypedefNameDecl;
183 class TypeLoc;
184 class TypoCorrectionConsumer;
185 class UnqualifiedId;
186 class UnresolvedLookupExpr;
187 class UnresolvedMemberExpr;
188 class UnresolvedSetImpl;
189 class UnresolvedSetIterator;
190 class UsingDecl;
191 class UsingShadowDecl;
192 class ValueDecl;
193 class VarDecl;
194 class VarTemplateSpecializationDecl;
195 class VisibilityAttr;
196 class VisibleDeclConsumer;
197 class IndirectFieldDecl;
198 struct DeductionFailureInfo;
199 class TemplateSpecCandidateSet;
200
201namespace sema {
202 class AccessedEntity;
203 class BlockScopeInfo;
204 class CapturedRegionScopeInfo;
205 class CapturingScopeInfo;
206 class CompoundScopeInfo;
207 class DelayedDiagnostic;
208 class DelayedDiagnosticPool;
209 class FunctionScopeInfo;
210 class LambdaScopeInfo;
211 class PossiblyUnreachableDiag;
212 class SemaPPCallbacks;
213 class TemplateDeductionInfo;
214}
215
216namespace threadSafety {
217 class BeforeSet;
218 void threadSafetyCleanup(BeforeSet* Cache);
219}
220
221// FIXME: No way to easily map from TemplateTypeParmTypes to
222// TemplateTypeParmDecls, so we have this horrible PointerUnion.
223typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
224 SourceLocation> UnexpandedParameterPack;
225
226/// Describes whether we've seen any nullability information for the given
227/// file.
228struct FileNullability {
229 /// The first pointer declarator (of any pointer kind) in the file that does
230 /// not have a corresponding nullability annotation.
231 SourceLocation PointerLoc;
232
233 /// The end location for the first pointer declarator in the file. Used for
234 /// placing fix-its.
235 SourceLocation PointerEndLoc;
236
237 /// Which kind of pointer declarator we saw.
238 uint8_t PointerKind;
239
240 /// Whether we saw any type nullability annotations in the given file.
241 bool SawTypeNullability = false;
242};
243
244/// A mapping from file IDs to a record of whether we've seen nullability
245/// information in that file.
246class FileNullabilityMap {
247 /// A mapping from file IDs to the nullability information for each file ID.
248 llvm::DenseMap<FileID, FileNullability> Map;
249
250 /// A single-element cache based on the file ID.
251 struct {
252 FileID File;
253 FileNullability Nullability;
254 } Cache;
255
256public:
257 FileNullability &operator[](FileID file) {
258 // Check the single-element cache.
259 if (file == Cache.File)
260 return Cache.Nullability;
261
262 // It's not in the single-element cache; flush the cache if we have one.
263 if (!Cache.File.isInvalid()) {
264 Map[Cache.File] = Cache.Nullability;
265 }
266
267 // Pull this entry into the cache.
268 Cache.File = file;
269 Cache.Nullability = Map[file];
270 return Cache.Nullability;
271 }
272};
273
274/// Sema - This implements semantic analysis and AST building for C.
275class Sema {
276 Sema(const Sema &) = delete;
277 void operator=(const Sema &) = delete;
278
279 ///\brief Source of additional semantic information.
280 ExternalSemaSource *ExternalSource;
281
282 ///\brief Whether Sema has generated a multiplexer and has to delete it.
283 bool isMultiplexExternalSource;
284
285 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
286
287 bool isVisibleSlow(const NamedDecl *D);
288
289 /// Determine whether two declarations should be linked together, given that
290 /// the old declaration might not be visible and the new declaration might
291 /// not have external linkage.
292 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
293 const NamedDecl *New) {
294 if (isVisible(Old))
295 return true;
296 // See comment in below overload for why it's safe to compute the linkage
297 // of the new declaration here.
298 if (New->isExternallyDeclarable()) {
299 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
300 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
;
301 return true;
302 }
303 return false;
304 }
305 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
306
307public:
308 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
309 typedef OpaquePtr<TemplateName> TemplateTy;
310 typedef OpaquePtr<QualType> TypeTy;
311
312 OpenCLOptions OpenCLFeatures;
313 FPOptions FPFeatures;
314
315 const LangOptions &LangOpts;
316 Preprocessor &PP;
317 ASTContext &Context;
318 ASTConsumer &Consumer;
319 DiagnosticsEngine &Diags;
320 SourceManager &SourceMgr;
321
322 /// \brief Flag indicating whether or not to collect detailed statistics.
323 bool CollectStats;
324
325 /// \brief Code-completion consumer.
326 CodeCompleteConsumer *CodeCompleter;
327
328 /// CurContext - This is the current declaration context of parsing.
329 DeclContext *CurContext;
330
331 /// \brief Generally null except when we temporarily switch decl contexts,
332 /// like in \see ActOnObjCTemporaryExitContainerContext.
333 DeclContext *OriginalLexicalContext;
334
335 /// VAListTagName - The declaration name corresponding to __va_list_tag.
336 /// This is used as part of a hack to omit that class from ADL results.
337 DeclarationName VAListTagName;
338
339 bool MSStructPragmaOn; // True when \#pragma ms_struct on
340
341 /// \brief Controls member pointer representation format under the MS ABI.
342 LangOptions::PragmaMSPointersToMembersKind
343 MSPointerToMemberRepresentationMethod;
344
345 /// Stack of active SEH __finally scopes. Can be empty.
346 SmallVector<Scope*, 2> CurrentSEHFinally;
347
348 /// \brief Source location for newly created implicit MSInheritanceAttrs
349 SourceLocation ImplicitMSInheritanceAttrLoc;
350
351 /// \brief pragma clang section kind
352 enum PragmaClangSectionKind {
353 PCSK_Invalid = 0,
354 PCSK_BSS = 1,
355 PCSK_Data = 2,
356 PCSK_Rodata = 3,
357 PCSK_Text = 4
358 };
359
360 enum PragmaClangSectionAction {
361 PCSA_Set = 0,
362 PCSA_Clear = 1
363 };
364
365 struct PragmaClangSection {
366 std::string SectionName;
367 bool Valid = false;
368 SourceLocation PragmaLocation;
369
370 void Act(SourceLocation PragmaLocation,
371 PragmaClangSectionAction Action,
372 StringLiteral* Name);
373 };
374
375 PragmaClangSection PragmaClangBSSSection;
376 PragmaClangSection PragmaClangDataSection;
377 PragmaClangSection PragmaClangRodataSection;
378 PragmaClangSection PragmaClangTextSection;
379
380 enum PragmaMsStackAction {
381 PSK_Reset = 0x0, // #pragma ()
382 PSK_Set = 0x1, // #pragma (value)
383 PSK_Push = 0x2, // #pragma (push[, id])
384 PSK_Pop = 0x4, // #pragma (pop[, id])
385 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
386 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
387 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
388 };
389
390 template<typename ValueType>
391 struct PragmaStack {
392 struct Slot {
393 llvm::StringRef StackSlotLabel;
394 ValueType Value;
395 SourceLocation PragmaLocation;
396 SourceLocation PragmaPushLocation;
397 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
398 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
399 : StackSlotLabel(StackSlotLabel), Value(Value),
400 PragmaLocation(PragmaLocation),
401 PragmaPushLocation(PragmaPushLocation) {}
402 };
403 void Act(SourceLocation PragmaLocation,
404 PragmaMsStackAction Action,
405 llvm::StringRef StackSlotLabel,
406 ValueType Value);
407
408 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
409 // method body to restore the stacks on exit, so it works like this:
410 //
411 // struct S {
412 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
413 // void Method {}
414 // #pragma <name>(pop, InternalPragmaSlot)
415 // };
416 //
417 // It works even with #pragma vtordisp, although MSVC doesn't support
418 // #pragma vtordisp(push [, id], n)
419 // syntax.
420 //
421 // Push / pop a named sentinel slot.
422 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
423 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
424 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
;
425 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
426 }
427
428 // Constructors.
429 explicit PragmaStack(const ValueType &Default)
430 : DefaultValue(Default), CurrentValue(Default) {}
431
432 bool hasValue() const { return CurrentValue != DefaultValue; }
433
434 SmallVector<Slot, 2> Stack;
435 ValueType DefaultValue; // Value used for PSK_Reset action.
436 ValueType CurrentValue;
437 SourceLocation CurrentPragmaLocation;
438 };
439 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
440 // we shouldn't do so if they're in a module).
441
442 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
443 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
444 ///
445 /// 0: Suppress all vtordisps
446 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
447 /// structors
448 /// 2: Always insert vtordisps to support RTTI on partially constructed
449 /// objects
450 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
451 // #pragma pack.
452 // Sentinel to represent when the stack is set to mac68k alignment.
453 static const unsigned kMac68kAlignmentSentinel = ~0U;
454 PragmaStack<unsigned> PackStack;
455 // The current #pragma pack values and locations at each #include.
456 struct PackIncludeState {
457 unsigned CurrentValue;
458 SourceLocation CurrentPragmaLocation;
459 bool HasNonDefaultValue, ShouldWarnOnInclude;
460 };
461 SmallVector<PackIncludeState, 8> PackIncludeStack;
462 // Segment #pragmas.
463 PragmaStack<StringLiteral *> DataSegStack;
464 PragmaStack<StringLiteral *> BSSSegStack;
465 PragmaStack<StringLiteral *> ConstSegStack;
466 PragmaStack<StringLiteral *> CodeSegStack;
467
468 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
469 // Actions should be performed only if we enter / exit a C++ method body.
470 class PragmaStackSentinelRAII {
471 public:
472 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
473 ~PragmaStackSentinelRAII();
474
475 private:
476 Sema &S;
477 StringRef SlotLabel;
478 bool ShouldAct;
479 };
480
481 /// A mapping that describes the nullability we've seen in each header file.
482 FileNullabilityMap NullabilityMap;
483
484 /// Last section used with #pragma init_seg.
485 StringLiteral *CurInitSeg;
486 SourceLocation CurInitSegLoc;
487
488 /// VisContext - Manages the stack for \#pragma GCC visibility.
489 void *VisContext; // Really a "PragmaVisStack*"
490
491 /// \brief This represents the stack of attributes that were pushed by
492 /// \#pragma clang attribute.
493 struct PragmaAttributeEntry {
494 SourceLocation Loc;
495 AttributeList *Attribute;
496 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
497 bool IsUsed;
498 };
499 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
500
501 /// \brief The declaration that is currently receiving an attribute from the
502 /// #pragma attribute stack.
503 const Decl *PragmaAttributeCurrentTargetDecl;
504
505 /// \brief This represents the last location of a "#pragma clang optimize off"
506 /// directive if such a directive has not been closed by an "on" yet. If
507 /// optimizations are currently "on", this is set to an invalid location.
508 SourceLocation OptimizeOffPragmaLocation;
509
510 /// \brief Flag indicating if Sema is building a recovery call expression.
511 ///
512 /// This flag is used to avoid building recovery call expressions
513 /// if Sema is already doing so, which would cause infinite recursions.
514 bool IsBuildingRecoveryCallExpr;
515
516 /// Used to control the generation of ExprWithCleanups.
517 CleanupInfo Cleanup;
518
519 /// ExprCleanupObjects - This is the stack of objects requiring
520 /// cleanup that are created by the current full expression. The
521 /// element type here is ExprWithCleanups::Object.
522 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
523
524 /// \brief Store a list of either DeclRefExprs or MemberExprs
525 /// that contain a reference to a variable (constant) that may or may not
526 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
527 /// and discarded value conversions have been applied to all subexpressions
528 /// of the enclosing full expression. This is cleared at the end of each
529 /// full expression.
530 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
531
532 /// \brief Stack containing information about each of the nested
533 /// function, block, and method scopes that are currently active.
534 ///
535 /// This array is never empty. Clients should ignore the first
536 /// element, which is used to cache a single FunctionScopeInfo
537 /// that's used to parse every top-level function.
538 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
539
540 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
541 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
542 ExtVectorDeclsType;
543
544 /// ExtVectorDecls - This is a list all the extended vector types. This allows
545 /// us to associate a raw vector type with one of the ext_vector type names.
546 /// This is only necessary for issuing pretty diagnostics.
547 ExtVectorDeclsType ExtVectorDecls;
548
549 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
550 std::unique_ptr<CXXFieldCollector> FieldCollector;
551
552 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
553
554 /// \brief Set containing all declared private fields that are not used.
555 NamedDeclSetType UnusedPrivateFields;
556
557 /// \brief Set containing all typedefs that are likely unused.
558 llvm::SmallSetVector<const TypedefNameDecl *, 4>
559 UnusedLocalTypedefNameCandidates;
560
561 /// \brief Delete-expressions to be analyzed at the end of translation unit
562 ///
563 /// This list contains class members, and locations of delete-expressions
564 /// that could not be proven as to whether they mismatch with new-expression
565 /// used in initializer of the field.
566 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
567 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
568 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
569
570 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
571
572 /// PureVirtualClassDiagSet - a set of class declarations which we have
573 /// emitted a list of pure virtual functions. Used to prevent emitting the
574 /// same list more than once.
575 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
576
577 /// ParsingInitForAutoVars - a set of declarations with auto types for which
578 /// we are currently parsing the initializer.
579 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
580
581 /// \brief Look for a locally scoped extern "C" declaration by the given name.
582 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
583
584 typedef LazyVector<VarDecl *, ExternalSemaSource,
585 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
586 TentativeDefinitionsType;
587
588 /// \brief All the tentative definitions encountered in the TU.
589 TentativeDefinitionsType TentativeDefinitions;
590
591 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
592 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
593 UnusedFileScopedDeclsType;
594
595 /// \brief The set of file scoped decls seen so far that have not been used
596 /// and must warn if not used. Only contains the first declaration.
597 UnusedFileScopedDeclsType UnusedFileScopedDecls;
598
599 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
600 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
601 DelegatingCtorDeclsType;
602
603 /// \brief All the delegating constructors seen so far in the file, used for
604 /// cycle detection at the end of the TU.
605 DelegatingCtorDeclsType DelegatingCtorDecls;
606
607 /// \brief All the overriding functions seen during a class definition
608 /// that had their exception spec checks delayed, plus the overridden
609 /// function.
610 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
611 DelayedExceptionSpecChecks;
612
613 /// \brief All the members seen during a class definition which were both
614 /// explicitly defaulted and had explicitly-specified exception
615 /// specifications, along with the function type containing their
616 /// user-specified exception specification. Those exception specifications
617 /// were overridden with the default specifications, but we still need to
618 /// check whether they are compatible with the default specification, and
619 /// we can't do that until the nesting set of class definitions is complete.
620 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
621 DelayedDefaultedMemberExceptionSpecs;
622
623 typedef llvm::MapVector<const FunctionDecl *,
624 std::unique_ptr<LateParsedTemplate>>
625 LateParsedTemplateMapT;
626 LateParsedTemplateMapT LateParsedTemplateMap;
627
628 /// \brief Callback to the parser to parse templated functions when needed.
629 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
630 typedef void LateTemplateParserCleanupCB(void *P);
631 LateTemplateParserCB *LateTemplateParser;
632 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
633 void *OpaqueParser;
634
635 void SetLateTemplateParser(LateTemplateParserCB *LTP,
636 LateTemplateParserCleanupCB *LTPCleanup,
637 void *P) {
638 LateTemplateParser = LTP;
639 LateTemplateParserCleanup = LTPCleanup;
640 OpaqueParser = P;
641 }
642
643 class DelayedDiagnostics;
644
645 class DelayedDiagnosticsState {
646 sema::DelayedDiagnosticPool *SavedPool;
647 friend class Sema::DelayedDiagnostics;
648 };
649 typedef DelayedDiagnosticsState ParsingDeclState;
650 typedef DelayedDiagnosticsState ProcessingContextState;
651
652 /// A class which encapsulates the logic for delaying diagnostics
653 /// during parsing and other processing.
654 class DelayedDiagnostics {
655 /// \brief The current pool of diagnostics into which delayed
656 /// diagnostics should go.
657 sema::DelayedDiagnosticPool *CurPool;
658
659 public:
660 DelayedDiagnostics() : CurPool(nullptr) {}
661
662 /// Adds a delayed diagnostic.
663 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
664
665 /// Determines whether diagnostics should be delayed.
666 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
667
668 /// Returns the current delayed-diagnostics pool.
669 sema::DelayedDiagnosticPool *getCurrentPool() const {
670 return CurPool;
671 }
672
673 /// Enter a new scope. Access and deprecation diagnostics will be
674 /// collected in this pool.
675 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
676 DelayedDiagnosticsState state;
677 state.SavedPool = CurPool;
678 CurPool = &pool;
679 return state;
680 }
681
682 /// Leave a delayed-diagnostic state that was previously pushed.
683 /// Do not emit any of the diagnostics. This is performed as part
684 /// of the bookkeeping of popping a pool "properly".
685 void popWithoutEmitting(DelayedDiagnosticsState state) {
686 CurPool = state.SavedPool;
687 }
688
689 /// Enter a new scope where access and deprecation diagnostics are
690 /// not delayed.
691 DelayedDiagnosticsState pushUndelayed() {
692 DelayedDiagnosticsState state;
693 state.SavedPool = CurPool;
694 CurPool = nullptr;
695 return state;
696 }
697
698 /// Undo a previous pushUndelayed().
699 void popUndelayed(DelayedDiagnosticsState state) {
700 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 700, __extension__ __PRETTY_FUNCTION__))
;
701 CurPool = state.SavedPool;
702 }
703 } DelayedDiagnostics;
704
705 /// A RAII object to temporarily push a declaration context.
706 class ContextRAII {
707 private:
708 Sema &S;
709 DeclContext *SavedContext;
710 ProcessingContextState SavedContextState;
711 QualType SavedCXXThisTypeOverride;
712
713 public:
714 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
715 : S(S), SavedContext(S.CurContext),
716 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
717 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
718 {
719 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 719, __extension__ __PRETTY_FUNCTION__))
;
720 S.CurContext = ContextToPush;
721 if (NewThisContext)
722 S.CXXThisTypeOverride = QualType();
723 }
724
725 void pop() {
726 if (!SavedContext) return;
727 S.CurContext = SavedContext;
728 S.DelayedDiagnostics.popUndelayed(SavedContextState);
729 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
730 SavedContext = nullptr;
731 }
732
733 ~ContextRAII() {
734 pop();
735 }
736 };
737
738 /// \brief RAII object to handle the state changes required to synthesize
739 /// a function body.
740 class SynthesizedFunctionScope {
741 Sema &S;
742 Sema::ContextRAII SavedContext;
743 bool PushedCodeSynthesisContext = false;
744
745 public:
746 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
747 : S(S), SavedContext(S, DC) {
748 S.PushFunctionScope();
749 S.PushExpressionEvaluationContext(
750 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
751 if (auto *FD = dyn_cast<FunctionDecl>(DC))
752 FD->setWillHaveBody(true);
753 else
754 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 754, __extension__ __PRETTY_FUNCTION__))
;
755 }
756
757 void addContextNote(SourceLocation UseLoc) {
758 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759
760 Sema::CodeSynthesisContext Ctx;
761 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
762 Ctx.PointOfInstantiation = UseLoc;
763 Ctx.Entity = cast<Decl>(S.CurContext);
764 S.pushCodeSynthesisContext(Ctx);
765
766 PushedCodeSynthesisContext = true;
767 }
768
769 ~SynthesizedFunctionScope() {
770 if (PushedCodeSynthesisContext)
771 S.popCodeSynthesisContext();
772 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
773 FD->setWillHaveBody(false);
774 S.PopExpressionEvaluationContext();
775 S.PopFunctionScopeInfo();
776 }
777 };
778
779 /// WeakUndeclaredIdentifiers - Identifiers contained in
780 /// \#pragma weak before declared. rare. may alias another
781 /// identifier, declared or undeclared
782 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
783
784 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
785 /// \#pragma redefine_extname before declared. Used in Solaris system headers
786 /// to define functions that occur in multiple standards to call the version
787 /// in the currently selected standard.
788 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
789
790
791 /// \brief Load weak undeclared identifiers from the external source.
792 void LoadExternalWeakUndeclaredIdentifiers();
793
794 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
795 /// \#pragma weak during processing of other Decls.
796 /// I couldn't figure out a clean way to generate these in-line, so
797 /// we store them here and handle separately -- which is a hack.
798 /// It would be best to refactor this.
799 SmallVector<Decl*,2> WeakTopLevelDecl;
800
801 IdentifierResolver IdResolver;
802
803 /// Translation Unit Scope - useful to Objective-C actions that need
804 /// to lookup file scope declarations in the "ordinary" C decl namespace.
805 /// For example, user-defined classes, built-in "id" type, etc.
806 Scope *TUScope;
807
808 /// \brief The C++ "std" namespace, where the standard library resides.
809 LazyDeclPtr StdNamespace;
810
811 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
812 /// standard library.
813 LazyDeclPtr StdBadAlloc;
814
815 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
816 /// standard library.
817 LazyDeclPtr StdAlignValT;
818
819 /// \brief The C++ "std::experimental" namespace, where the experimental parts
820 /// of the standard library resides.
821 NamespaceDecl *StdExperimentalNamespaceCache;
822
823 /// \brief The C++ "std::initializer_list" template, which is defined in
824 /// \<initializer_list>.
825 ClassTemplateDecl *StdInitializerList;
826
827 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
828 RecordDecl *CXXTypeInfoDecl;
829
830 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
831 RecordDecl *MSVCGuidDecl;
832
833 /// \brief Caches identifiers/selectors for NSFoundation APIs.
834 std::unique_ptr<NSAPI> NSAPIObj;
835
836 /// \brief The declaration of the Objective-C NSNumber class.
837 ObjCInterfaceDecl *NSNumberDecl;
838
839 /// \brief The declaration of the Objective-C NSValue class.
840 ObjCInterfaceDecl *NSValueDecl;
841
842 /// \brief Pointer to NSNumber type (NSNumber *).
843 QualType NSNumberPointer;
844
845 /// \brief Pointer to NSValue type (NSValue *).
846 QualType NSValuePointer;
847
848 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
849 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
850
851 /// \brief The declaration of the Objective-C NSString class.
852 ObjCInterfaceDecl *NSStringDecl;
853
854 /// \brief Pointer to NSString type (NSString *).
855 QualType NSStringPointer;
856
857 /// \brief The declaration of the stringWithUTF8String: method.
858 ObjCMethodDecl *StringWithUTF8StringMethod;
859
860 /// \brief The declaration of the valueWithBytes:objCType: method.
861 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
862
863 /// \brief The declaration of the Objective-C NSArray class.
864 ObjCInterfaceDecl *NSArrayDecl;
865
866 /// \brief The declaration of the arrayWithObjects:count: method.
867 ObjCMethodDecl *ArrayWithObjectsMethod;
868
869 /// \brief The declaration of the Objective-C NSDictionary class.
870 ObjCInterfaceDecl *NSDictionaryDecl;
871
872 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
873 ObjCMethodDecl *DictionaryWithObjectsMethod;
874
875 /// \brief id<NSCopying> type.
876 QualType QIDNSCopying;
877
878 /// \brief will hold 'respondsToSelector:'
879 Selector RespondsToSelectorSel;
880
881 /// A flag to remember whether the implicit forms of operator new and delete
882 /// have been declared.
883 bool GlobalNewDeleteDeclared;
884
885 /// A flag to indicate that we're in a context that permits abstract
886 /// references to fields. This is really a
887 bool AllowAbstractFieldReference;
888
889 /// \brief Describes how the expressions currently being parsed are
890 /// evaluated at run-time, if at all.
891 enum class ExpressionEvaluationContext {
892 /// \brief The current expression and its subexpressions occur within an
893 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
894 /// \c sizeof, where the type of the expression may be significant but
895 /// no code will be generated to evaluate the value of the expression at
896 /// run time.
897 Unevaluated,
898
899 /// \brief The current expression occurs within a braced-init-list within
900 /// an unevaluated operand. This is mostly like a regular unevaluated
901 /// context, except that we still instantiate constexpr functions that are
902 /// referenced here so that we can perform narrowing checks correctly.
903 UnevaluatedList,
904
905 /// \brief The current expression occurs within a discarded statement.
906 /// This behaves largely similarly to an unevaluated operand in preventing
907 /// definitions from being required, but not in other ways.
908 DiscardedStatement,
909
910 /// \brief The current expression occurs within an unevaluated
911 /// operand that unconditionally permits abstract references to
912 /// fields, such as a SIZE operator in MS-style inline assembly.
913 UnevaluatedAbstract,
914
915 /// \brief The current context is "potentially evaluated" in C++11 terms,
916 /// but the expression is evaluated at compile-time (like the values of
917 /// cases in a switch statement).
918 ConstantEvaluated,
919
920 /// \brief The current expression is potentially evaluated at run time,
921 /// which means that code may be generated to evaluate the value of the
922 /// expression at run time.
923 PotentiallyEvaluated,
924
925 /// \brief The current expression is potentially evaluated, but any
926 /// declarations referenced inside that expression are only used if
927 /// in fact the current expression is used.
928 ///
929 /// This value is used when parsing default function arguments, for which
930 /// we would like to provide diagnostics (e.g., passing non-POD arguments
931 /// through varargs) but do not want to mark declarations as "referenced"
932 /// until the default argument is used.
933 PotentiallyEvaluatedIfUsed
934 };
935
936 /// \brief Data structure used to record current or nested
937 /// expression evaluation contexts.
938 struct ExpressionEvaluationContextRecord {
939 /// \brief The expression evaluation context.
940 ExpressionEvaluationContext Context;
941
942 /// \brief Whether the enclosing context needed a cleanup.
943 CleanupInfo ParentCleanup;
944
945 /// \brief Whether we are in a decltype expression.
946 bool IsDecltype;
947
948 /// \brief The number of active cleanup objects when we entered
949 /// this expression evaluation context.
950 unsigned NumCleanupObjects;
951
952 /// \brief The number of typos encountered during this expression evaluation
953 /// context (i.e. the number of TypoExprs created).
954 unsigned NumTypos;
955
956 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
957
958 /// \brief The lambdas that are present within this context, if it
959 /// is indeed an unevaluated context.
960 SmallVector<LambdaExpr *, 2> Lambdas;
961
962 /// \brief The declaration that provides context for lambda expressions
963 /// and block literals if the normal declaration context does not
964 /// suffice, e.g., in a default function argument.
965 Decl *ManglingContextDecl;
966
967 /// \brief The context information used to mangle lambda expressions
968 /// and block literals within this context.
969 ///
970 /// This mangling information is allocated lazily, since most contexts
971 /// do not have lambda expressions or block literals.
972 std::unique_ptr<MangleNumberingContext> MangleNumbering;
973
974 /// \brief If we are processing a decltype type, a set of call expressions
975 /// for which we have deferred checking the completeness of the return type.
976 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
977
978 /// \brief If we are processing a decltype type, a set of temporary binding
979 /// expressions for which we have deferred checking the destructor.
980 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
981
982 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
983 unsigned NumCleanupObjects,
984 CleanupInfo ParentCleanup,
985 Decl *ManglingContextDecl,
986 bool IsDecltype)
987 : Context(Context), ParentCleanup(ParentCleanup),
988 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
989 NumTypos(0),
990 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
991
992 /// \brief Retrieve the mangling numbering context, used to consistently
993 /// number constructs like lambdas for mangling.
994 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
995
996 bool isUnevaluated() const {
997 return Context == ExpressionEvaluationContext::Unevaluated ||
998 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
999 Context == ExpressionEvaluationContext::UnevaluatedList;
1000 }
1001 bool isConstantEvaluated() const {
1002 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1003 }
1004 };
1005
1006 /// A stack of expression evaluation contexts.
1007 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1008
1009 /// \brief Compute the mangling number context for a lambda expression or
1010 /// block literal.
1011 ///
1012 /// \param DC - The DeclContext containing the lambda expression or
1013 /// block literal.
1014 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1015 /// associated with the context, if relevant.
1016 MangleNumberingContext *getCurrentMangleNumberContext(
1017 const DeclContext *DC,
1018 Decl *&ManglingContextDecl);
1019
1020
1021 /// SpecialMemberOverloadResult - The overloading result for a special member
1022 /// function.
1023 ///
1024 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1025 /// integer are used to determine whether overload resolution succeeded.
1026 class SpecialMemberOverloadResult {
1027 public:
1028 enum Kind {
1029 NoMemberOrDeleted,
1030 Ambiguous,
1031 Success
1032 };
1033
1034 private:
1035 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1036
1037 public:
1038 SpecialMemberOverloadResult() : Pair() {}
1039 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1040 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1041
1042 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1043 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1044
1045 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1046 void setKind(Kind K) { Pair.setInt(K); }
1047 };
1048
1049 class SpecialMemberOverloadResultEntry
1050 : public llvm::FastFoldingSetNode,
1051 public SpecialMemberOverloadResult {
1052 public:
1053 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1054 : FastFoldingSetNode(ID)
1055 {}
1056 };
1057
1058 /// \brief A cache of special member function overload resolution results
1059 /// for C++ records.
1060 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1061
1062 /// \brief A cache of the flags available in enumerations with the flag_bits
1063 /// attribute.
1064 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1065
1066 /// \brief The kind of translation unit we are processing.
1067 ///
1068 /// When we're processing a complete translation unit, Sema will perform
1069 /// end-of-translation-unit semantic tasks (such as creating
1070 /// initializers for tentative definitions in C) once parsing has
1071 /// completed. Modules and precompiled headers perform different kinds of
1072 /// checks.
1073 TranslationUnitKind TUKind;
1074
1075 llvm::BumpPtrAllocator BumpAlloc;
1076
1077 /// \brief The number of SFINAE diagnostics that have been trapped.
1078 unsigned NumSFINAEErrors;
1079
1080 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1081 UnparsedDefaultArgInstantiationsMap;
1082
1083 /// \brief A mapping from parameters with unparsed default arguments to the
1084 /// set of instantiations of each parameter.
1085 ///
1086 /// This mapping is a temporary data structure used when parsing
1087 /// nested class templates or nested classes of class templates,
1088 /// where we might end up instantiating an inner class before the
1089 /// default arguments of its methods have been parsed.
1090 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1091
1092 // Contains the locations of the beginning of unparsed default
1093 // argument locations.
1094 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1095
1096 /// UndefinedInternals - all the used, undefined objects which require a
1097 /// definition in this translation unit.
1098 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1099
1100 /// Determine if VD, which must be a variable or function, is an external
1101 /// symbol that nonetheless can't be referenced from outside this translation
1102 /// unit because its type has no linkage and it's not extern "C".
1103 bool isExternalWithNoLinkageType(ValueDecl *VD);
1104
1105 /// Obtain a sorted list of functions that are undefined but ODR-used.
1106 void getUndefinedButUsed(
1107 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1108
1109 /// Retrieves list of suspicious delete-expressions that will be checked at
1110 /// the end of translation unit.
1111 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1112 getMismatchingDeleteExpressions() const;
1113
1114 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1115 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1116
1117 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1118 /// We need to maintain a list, since selectors can have differing signatures
1119 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1120 /// of selectors are "overloaded").
1121 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1122 /// methods inside categories with a particular selector.
1123 GlobalMethodPool MethodPool;
1124
1125 /// Method selectors used in a \@selector expression. Used for implementation
1126 /// of -Wselector.
1127 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1128
1129 /// Kinds of C++ special members.
1130 enum CXXSpecialMember {
1131 CXXDefaultConstructor,
1132 CXXCopyConstructor,
1133 CXXMoveConstructor,
1134 CXXCopyAssignment,
1135 CXXMoveAssignment,
1136 CXXDestructor,
1137 CXXInvalid
1138 };
1139
1140 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1141 SpecialMemberDecl;
1142
1143 /// The C++ special members which we are currently in the process of
1144 /// declaring. If this process recursively triggers the declaration of the
1145 /// same special member, we should act as if it is not yet declared.
1146 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1147
1148 /// The function definitions which were renamed as part of typo-correction
1149 /// to match their respective declarations. We want to keep track of them
1150 /// to ensure that we don't emit a "redefinition" error if we encounter a
1151 /// correctly named definition after the renamed definition.
1152 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1153
1154 /// Stack of types that correspond to the parameter entities that are
1155 /// currently being copy-initialized. Can be empty.
1156 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1157
1158 void ReadMethodPool(Selector Sel);
1159 void updateOutOfDateSelector(Selector Sel);
1160
1161 /// Private Helper predicate to check for 'self'.
1162 bool isSelfExpr(Expr *RExpr);
1163 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1164
1165 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1166 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1167 /// should not be used elsewhere.
1168 void EmitCurrentDiagnostic(unsigned DiagID);
1169
1170 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1171 /// statements.
1172 class FPContractStateRAII {
1173 public:
1174 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1175 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1176
1177 private:
1178 Sema& S;
1179 FPOptions OldFPFeaturesState;
1180 };
1181
1182 void addImplicitTypedef(StringRef Name, QualType T);
1183
1184public:
1185 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1186 TranslationUnitKind TUKind = TU_Complete,
1187 CodeCompleteConsumer *CompletionConsumer = nullptr);
1188 ~Sema();
1189
1190 /// \brief Perform initialization that occurs after the parser has been
1191 /// initialized but before it parses anything.
1192 void Initialize();
1193
1194 const LangOptions &getLangOpts() const { return LangOpts; }
1195 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1196 FPOptions &getFPOptions() { return FPFeatures; }
1197
1198 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1199 SourceManager &getSourceManager() const { return SourceMgr; }
1200 Preprocessor &getPreprocessor() const { return PP; }
1201 ASTContext &getASTContext() const { return Context; }
1202 ASTConsumer &getASTConsumer() const { return Consumer; }
1203 ASTMutationListener *getASTMutationListener() const;
1204 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1205
1206 ///\brief Registers an external source. If an external source already exists,
1207 /// creates a multiplex external source and appends to it.
1208 ///
1209 ///\param[in] E - A non-null external sema source.
1210 ///
1211 void addExternalSource(ExternalSemaSource *E);
1212
1213 void PrintStats() const;
1214
1215 /// \brief Helper class that creates diagnostics with optional
1216 /// template instantiation stacks.
1217 ///
1218 /// This class provides a wrapper around the basic DiagnosticBuilder
1219 /// class that emits diagnostics. SemaDiagnosticBuilder is
1220 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1221 /// does) and, if the diagnostic comes from inside a template
1222 /// instantiation, printing the template instantiation stack as
1223 /// well.
1224 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1225 Sema &SemaRef;
1226 unsigned DiagID;
1227
1228 public:
1229 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1230 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1231
1232 // This is a cunning lie. DiagnosticBuilder actually performs move
1233 // construction in its copy constructor (but due to varied uses, it's not
1234 // possible to conveniently express this as actual move construction). So
1235 // the default copy ctor here is fine, because the base class disables the
1236 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1237 // in that case anwyay.
1238 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1239
1240 ~SemaDiagnosticBuilder() {
1241 // If we aren't active, there is nothing to do.
1242 if (!isActive()) return;
1243
1244 // Otherwise, we need to emit the diagnostic. First flush the underlying
1245 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1246 // won't emit the diagnostic in its own destructor.
1247 //
1248 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1249 // do its own needless checks to see if the diagnostic needs to be
1250 // emitted. However, because we take care to ensure that the builder
1251 // objects never escape, a sufficiently smart compiler will be able to
1252 // eliminate that code.
1253 FlushCounts();
1254 Clear();
1255
1256 // Dispatch to Sema to emit the diagnostic.
1257 SemaRef.EmitCurrentDiagnostic(DiagID);
1258 }
1259
1260 /// Teach operator<< to produce an object of the correct type.
1261 template<typename T>
1262 friend const SemaDiagnosticBuilder &operator<<(
1263 const SemaDiagnosticBuilder &Diag, const T &Value) {
1264 const DiagnosticBuilder &BaseDiag = Diag;
1265 BaseDiag << Value;
1266 return Diag;
1267 }
1268 };
1269
1270 /// \brief Emit a diagnostic.
1271 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1272 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1273 return SemaDiagnosticBuilder(DB, *this, DiagID);
1274 }
1275
1276 /// \brief Emit a partial diagnostic.
1277 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1278
1279 /// \brief Build a partial diagnostic.
1280 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1281
1282 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1283
1284 /// \brief Get a string to suggest for zero-initialization of a type.
1285 std::string
1286 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1287 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1288
1289 /// \brief Calls \c Lexer::getLocForEndOfToken()
1290 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1291
1292 /// \brief Retrieve the module loader associated with the preprocessor.
1293 ModuleLoader &getModuleLoader() const;
1294
1295 void emitAndClearUnusedLocalTypedefWarnings();
1296
1297 void ActOnStartOfTranslationUnit();
1298 void ActOnEndOfTranslationUnit();
1299
1300 void CheckDelegatingCtorCycles();
1301
1302 Scope *getScopeForContext(DeclContext *Ctx);
1303
1304 void PushFunctionScope();
1305 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1306 sema::LambdaScopeInfo *PushLambdaScope();
1307
1308 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1309 /// is during Parsing. Currently it is used to pass on the depth
1310 /// when parsing generic lambda 'auto' parameters.
1311 void RecordParsingTemplateParameterDepth(unsigned Depth);
1312
1313 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1314 RecordDecl *RD,
1315 CapturedRegionKind K);
1316 void
1317 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1318 const Decl *D = nullptr,
1319 const BlockExpr *blkExpr = nullptr);
1320
1321 sema::FunctionScopeInfo *getCurFunction() const {
1322 return FunctionScopes.back();
1323 }
1324
1325 sema::FunctionScopeInfo *getEnclosingFunction() const {
1326 if (FunctionScopes.empty())
1327 return nullptr;
1328
1329 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1330 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1331 continue;
1332 return FunctionScopes[e];
1333 }
1334 return nullptr;
1335 }
1336
1337 template <typename ExprT>
1338 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1339 if (!isUnevaluatedContext())
1340 getCurFunction()->recordUseOfWeak(E, IsRead);
1341 }
1342
1343 void PushCompoundScope(bool IsStmtExpr);
1344 void PopCompoundScope();
1345
1346 sema::CompoundScopeInfo &getCurCompoundScope() const;
1347
1348 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1349
1350 /// \brief Retrieve the current block, if any.
1351 sema::BlockScopeInfo *getCurBlock();
1352
1353 /// Retrieve the current lambda scope info, if any.
1354 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1355 /// lambda scope info ignoring all inner capturing scopes that are not
1356 /// lambda scopes.
1357 sema::LambdaScopeInfo *
1358 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1359
1360 /// \brief Retrieve the current generic lambda info, if any.
1361 sema::LambdaScopeInfo *getCurGenericLambda();
1362
1363 /// \brief Retrieve the current captured region, if any.
1364 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1365
1366 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1367 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1368
1369 void ActOnComment(SourceRange Comment);
1370
1371 //===--------------------------------------------------------------------===//
1372 // Type Analysis / Processing: SemaType.cpp.
1373 //
1374
1375 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1376 const DeclSpec *DS = nullptr);
1377 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1378 const DeclSpec *DS = nullptr);
1379 QualType BuildPointerType(QualType T,
1380 SourceLocation Loc, DeclarationName Entity);
1381 QualType BuildReferenceType(QualType T, bool LValueRef,
1382 SourceLocation Loc, DeclarationName Entity);
1383 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1384 Expr *ArraySize, unsigned Quals,
1385 SourceRange Brackets, DeclarationName Entity);
1386 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1387 SourceLocation AttrLoc);
1388 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1389 SourceLocation AttrLoc);
1390
1391 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1392
1393 /// \brief Build a function type.
1394 ///
1395 /// This routine checks the function type according to C++ rules and
1396 /// under the assumption that the result type and parameter types have
1397 /// just been instantiated from a template. It therefore duplicates
1398 /// some of the behavior of GetTypeForDeclarator, but in a much
1399 /// simpler form that is only suitable for this narrow use case.
1400 ///
1401 /// \param T The return type of the function.
1402 ///
1403 /// \param ParamTypes The parameter types of the function. This array
1404 /// will be modified to account for adjustments to the types of the
1405 /// function parameters.
1406 ///
1407 /// \param Loc The location of the entity whose type involves this
1408 /// function type or, if there is no such entity, the location of the
1409 /// type that will have function type.
1410 ///
1411 /// \param Entity The name of the entity that involves the function
1412 /// type, if known.
1413 ///
1414 /// \param EPI Extra information about the function type. Usually this will
1415 /// be taken from an existing function with the same prototype.
1416 ///
1417 /// \returns A suitable function type, if there are no errors. The
1418 /// unqualified type will always be a FunctionProtoType.
1419 /// Otherwise, returns a NULL type.
1420 QualType BuildFunctionType(QualType T,
1421 MutableArrayRef<QualType> ParamTypes,
1422 SourceLocation Loc, DeclarationName Entity,
1423 const FunctionProtoType::ExtProtoInfo &EPI);
1424
1425 QualType BuildMemberPointerType(QualType T, QualType Class,
1426 SourceLocation Loc,
1427 DeclarationName Entity);
1428 QualType BuildBlockPointerType(QualType T,
1429 SourceLocation Loc, DeclarationName Entity);
1430 QualType BuildParenType(QualType T);
1431 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1432 QualType BuildReadPipeType(QualType T,
1433 SourceLocation Loc);
1434 QualType BuildWritePipeType(QualType T,
1435 SourceLocation Loc);
1436
1437 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1438 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1439 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1440 TypeSourceInfo *ReturnTypeInfo);
1441
1442 /// \brief Package the given type and TSI into a ParsedType.
1443 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1444 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1445 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1446 static QualType GetTypeFromParser(ParsedType Ty,
1447 TypeSourceInfo **TInfo = nullptr);
1448 CanThrowResult canThrow(const Expr *E);
1449 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1450 const FunctionProtoType *FPT);
1451 void UpdateExceptionSpec(FunctionDecl *FD,
1452 const FunctionProtoType::ExceptionSpecInfo &ESI);
1453 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1454 bool CheckDistantExceptionSpec(QualType T);
1455 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1456 bool CheckEquivalentExceptionSpec(
1457 const FunctionProtoType *Old, SourceLocation OldLoc,
1458 const FunctionProtoType *New, SourceLocation NewLoc);
1459 bool CheckEquivalentExceptionSpec(
1460 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1461 const FunctionProtoType *Old, SourceLocation OldLoc,
1462 const FunctionProtoType *New, SourceLocation NewLoc);
1463 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1464 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1465 const PartialDiagnostic &NestedDiagID,
1466 const PartialDiagnostic &NoteID,
1467 const FunctionProtoType *Superset,
1468 SourceLocation SuperLoc,
1469 const FunctionProtoType *Subset,
1470 SourceLocation SubLoc);
1471 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1472 const PartialDiagnostic &NoteID,
1473 const FunctionProtoType *Target,
1474 SourceLocation TargetLoc,
1475 const FunctionProtoType *Source,
1476 SourceLocation SourceLoc);
1477
1478 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1479
1480 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1481 /// in an Objective-C message declaration. Return the appropriate type.
1482 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1483
1484 /// \brief Abstract class used to diagnose incomplete types.
1485 struct TypeDiagnoser {
1486 TypeDiagnoser() {}
1487
1488 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1489 virtual ~TypeDiagnoser() {}
1490 };
1491
1492 static int getPrintable(int I) { return I; }
1493 static unsigned getPrintable(unsigned I) { return I; }
1494 static bool getPrintable(bool B) { return B; }
1495 static const char * getPrintable(const char *S) { return S; }
1496 static StringRef getPrintable(StringRef S) { return S; }
1497 static const std::string &getPrintable(const std::string &S) { return S; }
1498 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1499 return II;
1500 }
1501 static DeclarationName getPrintable(DeclarationName N) { return N; }
1502 static QualType getPrintable(QualType T) { return T; }
1503 static SourceRange getPrintable(SourceRange R) { return R; }
1504 static SourceRange getPrintable(SourceLocation L) { return L; }
1505 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1506 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1507
1508 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1509 unsigned DiagID;
1510 std::tuple<const Ts &...> Args;
1511
1512 template <std::size_t... Is>
1513 void emit(const SemaDiagnosticBuilder &DB,
1514 llvm::index_sequence<Is...>) const {
1515 // Apply all tuple elements to the builder in order.
1516 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1517 (void)Dummy;
1518 }
1519
1520 public:
1521 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1522 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1523 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 1523, __extension__ __PRETTY_FUNCTION__))
;
1524 }
1525
1526 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1527 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1528 emit(DB, llvm::index_sequence_for<Ts...>());
1529 DB << T;
1530 }
1531 };
1532
1533private:
1534 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1535 TypeDiagnoser *Diagnoser);
1536
1537 struct ModuleScope {
1538 clang::Module *Module = nullptr;
1539 bool ModuleInterface = false;
1540 VisibleModuleSet OuterVisibleModules;
1541 };
1542 /// The modules we're currently parsing.
1543 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1544
1545 /// Get the module whose scope we are currently within.
1546 Module *getCurrentModule() const {
1547 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1548 }
1549
1550 VisibleModuleSet VisibleModules;
1551
1552public:
1553 /// \brief Get the module owning an entity.
1554 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1555
1556 /// \brief Make a merged definition of an existing hidden definition \p ND
1557 /// visible at the specified location.
1558 void makeMergedDefinitionVisible(NamedDecl *ND);
1559
1560 bool isModuleVisible(const Module *M) { return VisibleModules.isVisible(M); }
1561
1562 /// Determine whether a declaration is visible to name lookup.
1563 bool isVisible(const NamedDecl *D) {
1564 return !D->isHidden() || isVisibleSlow(D);
1565 }
1566
1567 /// Determine whether any declaration of an entity is visible.
1568 bool
1569 hasVisibleDeclaration(const NamedDecl *D,
1570 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1571 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1572 }
1573 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1574 llvm::SmallVectorImpl<Module *> *Modules);
1575
1576 bool hasVisibleMergedDefinition(NamedDecl *Def);
1577 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1578
1579 /// Determine if \p D and \p Suggested have a structurally compatible
1580 /// layout as described in C11 6.2.7/1.
1581 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1582
1583 /// Determine if \p D has a visible definition. If not, suggest a declaration
1584 /// that should be made visible to expose the definition.
1585 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1586 bool OnlyNeedComplete = false);
1587 bool hasVisibleDefinition(const NamedDecl *D) {
1588 NamedDecl *Hidden;
1589 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1590 }
1591
1592 /// Determine if the template parameter \p D has a visible default argument.
1593 bool
1594 hasVisibleDefaultArgument(const NamedDecl *D,
1595 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1596
1597 /// Determine if there is a visible declaration of \p D that is an explicit
1598 /// specialization declaration for a specialization of a template. (For a
1599 /// member specialization, use hasVisibleMemberSpecialization.)
1600 bool hasVisibleExplicitSpecialization(
1601 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1602
1603 /// Determine if there is a visible declaration of \p D that is a member
1604 /// specialization declaration (as opposed to an instantiated declaration).
1605 bool hasVisibleMemberSpecialization(
1606 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1607
1608 /// Determine if \p A and \p B are equivalent internal linkage declarations
1609 /// from different modules, and thus an ambiguity error can be downgraded to
1610 /// an extension warning.
1611 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1612 const NamedDecl *B);
1613 void diagnoseEquivalentInternalLinkageDeclarations(
1614 SourceLocation Loc, const NamedDecl *D,
1615 ArrayRef<const NamedDecl *> Equiv);
1616
1617 bool isCompleteType(SourceLocation Loc, QualType T) {
1618 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1619 }
1620 bool RequireCompleteType(SourceLocation Loc, QualType T,
1621 TypeDiagnoser &Diagnoser);
1622 bool RequireCompleteType(SourceLocation Loc, QualType T,
1623 unsigned DiagID);
1624
1625 template <typename... Ts>
1626 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1627 const Ts &...Args) {
1628 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1629 return RequireCompleteType(Loc, T, Diagnoser);
1630 }
1631
1632 void completeExprArrayBound(Expr *E);
1633 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1634 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1635
1636 template <typename... Ts>
1637 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1638 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1639 return RequireCompleteExprType(E, Diagnoser);
1640 }
1641
1642 bool RequireLiteralType(SourceLocation Loc, QualType T,
1643 TypeDiagnoser &Diagnoser);
1644 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1645
1646 template <typename... Ts>
1647 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1648 const Ts &...Args) {
1649 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1650 return RequireLiteralType(Loc, T, Diagnoser);
1651 }
1652
1653 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1654 const CXXScopeSpec &SS, QualType T);
1655
1656 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1657 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1658 /// context, such as when building a type for decltype(auto).
1659 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1660 bool AsUnevaluated = true);
1661 QualType BuildUnaryTransformType(QualType BaseType,
1662 UnaryTransformType::UTTKind UKind,
1663 SourceLocation Loc);
1664
1665 //===--------------------------------------------------------------------===//
1666 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1667 //
1668
1669 struct SkipBodyInfo {
1670 SkipBodyInfo()
1671 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1672 New(nullptr) {}
1673 bool ShouldSkip;
1674 bool CheckSameAsPrevious;
1675 NamedDecl *Previous;
1676 NamedDecl *New;
1677 };
1678
1679 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1680
1681 void DiagnoseUseOfUnimplementedSelectors();
1682
1683 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1684
1685 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1686 Scope *S, CXXScopeSpec *SS = nullptr,
1687 bool isClassName = false, bool HasTrailingDot = false,
1688 ParsedType ObjectType = nullptr,
1689 bool IsCtorOrDtorName = false,
1690 bool WantNontrivialTypeSourceInfo = false,
1691 bool IsClassTemplateDeductionContext = true,
1692 IdentifierInfo **CorrectedII = nullptr);
1693 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1694 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1695 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1696 SourceLocation IILoc,
1697 Scope *S,
1698 CXXScopeSpec *SS,
1699 ParsedType &SuggestedType,
1700 bool IsTemplateName = false);
1701
1702 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1703 /// type name has failed in a dependent context. In these situations, we
1704 /// automatically form a DependentTypeName that will retry lookup in a related
1705 /// scope during instantiation.
1706 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1707 SourceLocation NameLoc,
1708 bool IsTemplateTypeArg);
1709
1710 /// \brief Describes the result of the name lookup and resolution performed
1711 /// by \c ClassifyName().
1712 enum NameClassificationKind {
1713 NC_Unknown,
1714 NC_Error,
1715 NC_Keyword,
1716 NC_Type,
1717 NC_Expression,
1718 NC_NestedNameSpecifier,
1719 NC_TypeTemplate,
1720 NC_VarTemplate,
1721 NC_FunctionTemplate
1722 };
1723
1724 class NameClassification {
1725 NameClassificationKind Kind;
1726 ExprResult Expr;
1727 TemplateName Template;
1728 ParsedType Type;
1729
1730 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1731
1732 public:
1733 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1734
1735 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1736
1737 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1738
1739 static NameClassification Error() {
1740 return NameClassification(NC_Error);
1741 }
1742
1743 static NameClassification Unknown() {
1744 return NameClassification(NC_Unknown);
1745 }
1746
1747 static NameClassification NestedNameSpecifier() {
1748 return NameClassification(NC_NestedNameSpecifier);
1749 }
1750
1751 static NameClassification TypeTemplate(TemplateName Name) {
1752 NameClassification Result(NC_TypeTemplate);
1753 Result.Template = Name;
1754 return Result;
1755 }
1756
1757 static NameClassification VarTemplate(TemplateName Name) {
1758 NameClassification Result(NC_VarTemplate);
1759 Result.Template = Name;
1760 return Result;
1761 }
1762
1763 static NameClassification FunctionTemplate(TemplateName Name) {
1764 NameClassification Result(NC_FunctionTemplate);
1765 Result.Template = Name;
1766 return Result;
1767 }
1768
1769 NameClassificationKind getKind() const { return Kind; }
1770
1771 ParsedType getType() const {
1772 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 1772, __extension__ __PRETTY_FUNCTION__))
;
1773 return Type;
1774 }
1775
1776 ExprResult getExpression() const {
1777 assert(Kind == NC_Expression)(static_cast <bool> (Kind == NC_Expression) ? void (0) :
__assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 1777, __extension__ __PRETTY_FUNCTION__))
;
1778 return Expr;
1779 }
1780
1781 TemplateName getTemplateName() const {
1782 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 1783, __extension__ __PRETTY_FUNCTION__))
1783 Kind == NC_VarTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 1783, __extension__ __PRETTY_FUNCTION__))
;
1784 return Template;
1785 }
1786
1787 TemplateNameKind getTemplateNameKind() const {
1788 switch (Kind) {
1789 case NC_TypeTemplate:
1790 return TNK_Type_template;
1791 case NC_FunctionTemplate:
1792 return TNK_Function_template;
1793 case NC_VarTemplate:
1794 return TNK_Var_template;
1795 default:
1796 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 1796)
;
1797 }
1798 }
1799 };
1800
1801 /// \brief Perform name lookup on the given name, classifying it based on
1802 /// the results of name lookup and the following token.
1803 ///
1804 /// This routine is used by the parser to resolve identifiers and help direct
1805 /// parsing. When the identifier cannot be found, this routine will attempt
1806 /// to correct the typo and classify based on the resulting name.
1807 ///
1808 /// \param S The scope in which we're performing name lookup.
1809 ///
1810 /// \param SS The nested-name-specifier that precedes the name.
1811 ///
1812 /// \param Name The identifier. If typo correction finds an alternative name,
1813 /// this pointer parameter will be updated accordingly.
1814 ///
1815 /// \param NameLoc The location of the identifier.
1816 ///
1817 /// \param NextToken The token following the identifier. Used to help
1818 /// disambiguate the name.
1819 ///
1820 /// \param IsAddressOfOperand True if this name is the operand of a unary
1821 /// address of ('&') expression, assuming it is classified as an
1822 /// expression.
1823 ///
1824 /// \param CCC The correction callback, if typo correction is desired.
1825 NameClassification
1826 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1827 SourceLocation NameLoc, const Token &NextToken,
1828 bool IsAddressOfOperand,
1829 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1830
1831 /// Describes the detailed kind of a template name. Used in diagnostics.
1832 enum class TemplateNameKindForDiagnostics {
1833 ClassTemplate,
1834 FunctionTemplate,
1835 VarTemplate,
1836 AliasTemplate,
1837 TemplateTemplateParam,
1838 DependentTemplate
1839 };
1840 TemplateNameKindForDiagnostics
1841 getTemplateNameKindForDiagnostics(TemplateName Name);
1842
1843 /// Determine whether it's plausible that E was intended to be a
1844 /// template-name.
1845 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1846 if (!getLangOpts().CPlusPlus || E.isInvalid())
1847 return false;
1848 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1849 return !DRE->hasExplicitTemplateArgs();
1850 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1851 return !ME->hasExplicitTemplateArgs();
1852 // Any additional cases recognized here should also be handled by
1853 // diagnoseExprIntendedAsTemplateName.
1854 return false;
1855 }
1856 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1857 SourceLocation Less,
1858 SourceLocation Greater);
1859
1860 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1861
1862 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1863 MultiTemplateParamsArg TemplateParameterLists);
1864 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1865 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1866 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1867 DeclarationName Name,
1868 SourceLocation Loc);
1869 void
1870 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1871 SourceLocation FallbackLoc,
1872 SourceLocation ConstQualLoc = SourceLocation(),
1873 SourceLocation VolatileQualLoc = SourceLocation(),
1874 SourceLocation RestrictQualLoc = SourceLocation(),
1875 SourceLocation AtomicQualLoc = SourceLocation(),
1876 SourceLocation UnalignedQualLoc = SourceLocation());
1877
1878 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1879 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1880 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1881 const LookupResult &R);
1882 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1883 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1884 const LookupResult &R);
1885 void CheckShadow(Scope *S, VarDecl *D);
1886
1887 /// Warn if 'E', which is an expression that is about to be modified, refers
1888 /// to a shadowing declaration.
1889 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1890
1891 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1892
1893private:
1894 /// Map of current shadowing declarations to shadowed declarations. Warn if
1895 /// it looks like the user is trying to modify the shadowing declaration.
1896 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1897
1898public:
1899 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1900 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1901 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1902 TypedefNameDecl *NewTD);
1903 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1904 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1905 TypeSourceInfo *TInfo,
1906 LookupResult &Previous);
1907 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1908 LookupResult &Previous, bool &Redeclaration);
1909 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1910 TypeSourceInfo *TInfo,
1911 LookupResult &Previous,
1912 MultiTemplateParamsArg TemplateParamLists,
1913 bool &AddToScope,
1914 ArrayRef<BindingDecl *> Bindings = None);
1915 NamedDecl *
1916 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1917 MultiTemplateParamsArg TemplateParamLists);
1918 // Returns true if the variable declaration is a redeclaration
1919 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1920 void CheckVariableDeclarationType(VarDecl *NewVD);
1921 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1922 Expr *Init);
1923 void CheckCompleteVariableDeclaration(VarDecl *VD);
1924 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1925 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1926
1927 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1928 TypeSourceInfo *TInfo,
1929 LookupResult &Previous,
1930 MultiTemplateParamsArg TemplateParamLists,
1931 bool &AddToScope);
1932 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1933
1934 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1935 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1936
1937 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1938 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1939 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1940 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1941 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1942 // Returns true if the function declaration is a redeclaration
1943 bool CheckFunctionDeclaration(Scope *S,
1944 FunctionDecl *NewFD, LookupResult &Previous,
1945 bool IsMemberSpecialization);
1946 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1947 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1948 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1949 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1950 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1951 SourceLocation Loc,
1952 QualType T);
1953 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1954 SourceLocation NameLoc, IdentifierInfo *Name,
1955 QualType T, TypeSourceInfo *TSInfo,
1956 StorageClass SC);
1957 void ActOnParamDefaultArgument(Decl *param,
1958 SourceLocation EqualLoc,
1959 Expr *defarg);
1960 void ActOnParamUnparsedDefaultArgument(Decl *param,
1961 SourceLocation EqualLoc,
1962 SourceLocation ArgLoc);
1963 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1964 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1965 SourceLocation EqualLoc);
1966
1967 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1968 void ActOnUninitializedDecl(Decl *dcl);
1969 void ActOnInitializerError(Decl *Dcl);
1970
1971 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1972 void ActOnCXXForRangeDecl(Decl *D);
1973 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1974 IdentifierInfo *Ident,
1975 ParsedAttributes &Attrs,
1976 SourceLocation AttrEnd);
1977 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1978 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1979 void FinalizeDeclaration(Decl *D);
1980 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1981 ArrayRef<Decl *> Group);
1982 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1983
1984 /// Should be called on all declarations that might have attached
1985 /// documentation comments.
1986 void ActOnDocumentableDecl(Decl *D);
1987 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1988
1989 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1990 SourceLocation LocAfterDecls);
1991 void CheckForFunctionRedefinition(
1992 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1993 SkipBodyInfo *SkipBody = nullptr);
1994 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1995 MultiTemplateParamsArg TemplateParamLists,
1996 SkipBodyInfo *SkipBody = nullptr);
1997 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1998 SkipBodyInfo *SkipBody = nullptr);
1999 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2000 bool isObjCMethodDecl(Decl *D) {
2001 return D && isa<ObjCMethodDecl>(D);
2002 }
2003
2004 /// \brief Determine whether we can delay parsing the body of a function or
2005 /// function template until it is used, assuming we don't care about emitting
2006 /// code for that function.
2007 ///
2008 /// This will be \c false if we may need the body of the function in the
2009 /// middle of parsing an expression (where it's impractical to switch to
2010 /// parsing a different function), for instance, if it's constexpr in C++11
2011 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2012 bool canDelayFunctionBody(const Declarator &D);
2013
2014 /// \brief Determine whether we can skip parsing the body of a function
2015 /// definition, assuming we don't care about analyzing its body or emitting
2016 /// code for that function.
2017 ///
2018 /// This will be \c false only if we may need the body of the function in
2019 /// order to parse the rest of the program (for instance, if it is
2020 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2021 bool canSkipFunctionBody(Decl *D);
2022
2023 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2024 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2025 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2026 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2027 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2028
2029 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2030 /// attribute for which parsing is delayed.
2031 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2032
2033 /// \brief Diagnose any unused parameters in the given sequence of
2034 /// ParmVarDecl pointers.
2035 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2036
2037 /// \brief Diagnose whether the size of parameters or return value of a
2038 /// function or obj-c method definition is pass-by-value and larger than a
2039 /// specified threshold.
2040 void
2041 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2042 QualType ReturnTy, NamedDecl *D);
2043
2044 void DiagnoseInvalidJumps(Stmt *Body);
2045 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2046 SourceLocation AsmLoc,
2047 SourceLocation RParenLoc);
2048
2049 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
2050 Decl *ActOnEmptyDeclaration(Scope *S,
2051 AttributeList *AttrList,
2052 SourceLocation SemiLoc);
2053
2054 enum class ModuleDeclKind {
2055 Interface, ///< 'export module X;'
2056 Implementation, ///< 'module X;'
2057 Partition, ///< 'module partition X;'
2058 };
2059
2060 /// The parser has processed a module-declaration that begins the definition
2061 /// of a module interface or implementation.
2062 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2063 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2064 ModuleIdPath Path);
2065
2066 /// \brief The parser has processed a module import declaration.
2067 ///
2068 /// \param AtLoc The location of the '@' symbol, if any.
2069 ///
2070 /// \param ImportLoc The location of the 'import' keyword.
2071 ///
2072 /// \param Path The module access path.
2073 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2074 ModuleIdPath Path);
2075
2076 /// \brief The parser has processed a module import translated from a
2077 /// #include or similar preprocessing directive.
2078 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2079 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2080
2081 /// \brief The parsed has entered a submodule.
2082 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2083 /// \brief The parser has left a submodule.
2084 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2085
2086 /// \brief Create an implicit import of the given module at the given
2087 /// source location, for error recovery, if possible.
2088 ///
2089 /// This routine is typically used when an entity found by name lookup
2090 /// is actually hidden within a module that we know about but the user
2091 /// has forgotten to import.
2092 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2093 Module *Mod);
2094
2095 /// Kinds of missing import. Note, the values of these enumerators correspond
2096 /// to %select values in diagnostics.
2097 enum class MissingImportKind {
2098 Declaration,
2099 Definition,
2100 DefaultArgument,
2101 ExplicitSpecialization,
2102 PartialSpecialization
2103 };
2104
2105 /// \brief Diagnose that the specified declaration needs to be visible but
2106 /// isn't, and suggest a module import that would resolve the problem.
2107 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2108 MissingImportKind MIK, bool Recover = true);
2109 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2110 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2111 MissingImportKind MIK, bool Recover);
2112
2113 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2114 SourceLocation LBraceLoc);
2115 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2116 SourceLocation RBraceLoc);
2117
2118 /// \brief We've found a use of a templated declaration that would trigger an
2119 /// implicit instantiation. Check that any relevant explicit specializations
2120 /// and partial specializations are visible, and diagnose if not.
2121 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2122
2123 /// \brief We've found a use of a template specialization that would select a
2124 /// partial specialization. Check that the partial specialization is visible,
2125 /// and diagnose if not.
2126 void checkPartialSpecializationVisibility(SourceLocation Loc,
2127 NamedDecl *Spec);
2128
2129 /// \brief Retrieve a suitable printing policy.
2130 PrintingPolicy getPrintingPolicy() const {
2131 return getPrintingPolicy(Context, PP);
2132 }
2133
2134 /// \brief Retrieve a suitable printing policy.
2135 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2136 const Preprocessor &PP);
2137
2138 /// Scope actions.
2139 void ActOnPopScope(SourceLocation Loc, Scope *S);
2140 void ActOnTranslationUnitScope(Scope *S);
2141
2142 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2143 RecordDecl *&AnonRecord);
2144 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2145 MultiTemplateParamsArg TemplateParams,
2146 bool IsExplicitInstantiation,
2147 RecordDecl *&AnonRecord);
2148
2149 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2150 AccessSpecifier AS,
2151 RecordDecl *Record,
2152 const PrintingPolicy &Policy);
2153
2154 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2155 RecordDecl *Record);
2156
2157 /// Common ways to introduce type names without a tag for use in diagnostics.
2158 /// Keep in sync with err_tag_reference_non_tag.
2159 enum NonTagKind {
2160 NTK_NonStruct,
2161 NTK_NonClass,
2162 NTK_NonUnion,
2163 NTK_NonEnum,
2164 NTK_Typedef,
2165 NTK_TypeAlias,
2166 NTK_Template,
2167 NTK_TypeAliasTemplate,
2168 NTK_TemplateTemplateArgument,
2169 };
2170
2171 /// Given a non-tag type declaration, returns an enum useful for indicating
2172 /// what kind of non-tag type this is.
2173 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2174
2175 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2176 TagTypeKind NewTag, bool isDefinition,
2177 SourceLocation NewTagLoc,
2178 const IdentifierInfo *Name);
2179
2180 enum TagUseKind {
2181 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2182 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2183 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2184 TUK_Friend // Friend declaration: 'friend struct foo;'
2185 };
2186
2187 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2188 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2189 SourceLocation NameLoc, AttributeList *Attr,
2190 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2191 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2192 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2193 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2194 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2195 SkipBodyInfo *SkipBody = nullptr);
2196
2197 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2198 unsigned TagSpec, SourceLocation TagLoc,
2199 CXXScopeSpec &SS,
2200 IdentifierInfo *Name, SourceLocation NameLoc,
2201 AttributeList *Attr,
2202 MultiTemplateParamsArg TempParamLists);
2203
2204 TypeResult ActOnDependentTag(Scope *S,
2205 unsigned TagSpec,
2206 TagUseKind TUK,
2207 const CXXScopeSpec &SS,
2208 IdentifierInfo *Name,
2209 SourceLocation TagLoc,
2210 SourceLocation NameLoc);
2211
2212 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2213 IdentifierInfo *ClassName,
2214 SmallVectorImpl<Decl *> &Decls);
2215 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2216 Declarator &D, Expr *BitfieldWidth);
2217
2218 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2219 Declarator &D, Expr *BitfieldWidth,
2220 InClassInitStyle InitStyle,
2221 AccessSpecifier AS);
2222 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2223 SourceLocation DeclStart,
2224 Declarator &D, Expr *BitfieldWidth,
2225 InClassInitStyle InitStyle,
2226 AccessSpecifier AS,
2227 AttributeList *MSPropertyAttr);
2228
2229 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2230 TypeSourceInfo *TInfo,
2231 RecordDecl *Record, SourceLocation Loc,
2232 bool Mutable, Expr *BitfieldWidth,
2233 InClassInitStyle InitStyle,
2234 SourceLocation TSSL,
2235 AccessSpecifier AS, NamedDecl *PrevDecl,
2236 Declarator *D = nullptr);
2237
2238 bool CheckNontrivialField(FieldDecl *FD);
2239 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2240
2241 enum TrivialABIHandling {
2242 /// The triviality of a method unaffected by "trivial_abi".
2243 TAH_IgnoreTrivialABI,
2244
2245 /// The triviality of a method affected by "trivial_abi".
2246 TAH_ConsiderTrivialABI
2247 };
2248
2249 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2250 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2251 bool Diagnose = false);
2252 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2253 void ActOnLastBitfield(SourceLocation DeclStart,
2254 SmallVectorImpl<Decl *> &AllIvarDecls);
2255 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2256 Declarator &D, Expr *BitfieldWidth,
2257 tok::ObjCKeywordKind visibility);
2258
2259 // This is used for both record definitions and ObjC interface declarations.
2260 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2261 ArrayRef<Decl *> Fields,
2262 SourceLocation LBrac, SourceLocation RBrac,
2263 AttributeList *AttrList);
2264
2265 /// ActOnTagStartDefinition - Invoked when we have entered the
2266 /// scope of a tag's definition (e.g., for an enumeration, class,
2267 /// struct, or union).
2268 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2269
2270 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2271 /// Differently from C++, actually parse the body and reject / error out
2272 /// in case of a structural mismatch.
2273 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2274 SkipBodyInfo &SkipBody);
2275
2276 typedef void *SkippedDefinitionContext;
2277
2278 /// \brief Invoked when we enter a tag definition that we're skipping.
2279 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2280
2281 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2282
2283 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2284 /// C++ record definition's base-specifiers clause and are starting its
2285 /// member declarations.
2286 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2287 SourceLocation FinalLoc,
2288 bool IsFinalSpelledSealed,
2289 SourceLocation LBraceLoc);
2290
2291 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2292 /// the definition of a tag (enumeration, class, struct, or union).
2293 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2294 SourceRange BraceRange);
2295
2296 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2297
2298 void ActOnObjCContainerFinishDefinition();
2299
2300 /// \brief Invoked when we must temporarily exit the objective-c container
2301 /// scope for parsing/looking-up C constructs.
2302 ///
2303 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2304 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2305 void ActOnObjCReenterContainerContext(DeclContext *DC);
2306
2307 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2308 /// error parsing the definition of a tag.
2309 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2310
2311 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2312 EnumConstantDecl *LastEnumConst,
2313 SourceLocation IdLoc,
2314 IdentifierInfo *Id,
2315 Expr *val);
2316 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2317 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2318 QualType EnumUnderlyingTy, bool IsFixed,
2319 const EnumDecl *Prev);
2320
2321 /// Determine whether the body of an anonymous enumeration should be skipped.
2322 /// \param II The name of the first enumerator.
2323 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2324 SourceLocation IILoc);
2325
2326 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2327 SourceLocation IdLoc, IdentifierInfo *Id,
2328 AttributeList *Attrs, SourceLocation EqualLoc,
2329 Expr *Val);
2330 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2331 Decl *EnumDecl,
2332 ArrayRef<Decl *> Elements,
2333 Scope *S, AttributeList *Attr);
2334
2335 DeclContext *getContainingDC(DeclContext *DC);
2336
2337 /// Set the current declaration context until it gets popped.
2338 void PushDeclContext(Scope *S, DeclContext *DC);
2339 void PopDeclContext();
2340
2341 /// EnterDeclaratorContext - Used when we must lookup names in the context
2342 /// of a declarator's nested name specifier.
2343 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2344 void ExitDeclaratorContext(Scope *S);
2345
2346 /// Push the parameters of D, which must be a function, into scope.
2347 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2348 void ActOnExitFunctionContext();
2349
2350 DeclContext *getFunctionLevelDeclContext();
2351
2352 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2353 /// to the function decl for the function being parsed. If we're currently
2354 /// in a 'block', this returns the containing context.
2355 FunctionDecl *getCurFunctionDecl();
2356
2357 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2358 /// the method decl for the method being parsed. If we're currently
2359 /// in a 'block', this returns the containing context.
2360 ObjCMethodDecl *getCurMethodDecl();
2361
2362 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2363 /// or C function we're in, otherwise return null. If we're currently
2364 /// in a 'block', this returns the containing context.
2365 NamedDecl *getCurFunctionOrMethodDecl();
2366
2367 /// Add this decl to the scope shadowed decl chains.
2368 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2369
2370 /// \brief Make the given externally-produced declaration visible at the
2371 /// top level scope.
2372 ///
2373 /// \param D The externally-produced declaration to push.
2374 ///
2375 /// \param Name The name of the externally-produced declaration.
2376 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2377
2378 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2379 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2380 /// true if 'D' belongs to the given declaration context.
2381 ///
2382 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2383 /// enclosing namespace set of the context, rather than contained
2384 /// directly within it.
2385 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2386 bool AllowInlineNamespace = false);
2387
2388 /// Finds the scope corresponding to the given decl context, if it
2389 /// happens to be an enclosing scope. Otherwise return NULL.
2390 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2391
2392 /// Subroutines of ActOnDeclarator().
2393 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2394 TypeSourceInfo *TInfo);
2395 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2396
2397 /// \brief Describes the kind of merge to perform for availability
2398 /// attributes (including "deprecated", "unavailable", and "availability").
2399 enum AvailabilityMergeKind {
2400 /// \brief Don't merge availability attributes at all.
2401 AMK_None,
2402 /// \brief Merge availability attributes for a redeclaration, which requires
2403 /// an exact match.
2404 AMK_Redeclaration,
2405 /// \brief Merge availability attributes for an override, which requires
2406 /// an exact match or a weakening of constraints.
2407 AMK_Override,
2408 /// \brief Merge availability attributes for an implementation of
2409 /// a protocol requirement.
2410 AMK_ProtocolImplementation,
2411 };
2412
2413 /// Attribute merging methods. Return true if a new attribute was added.
2414 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2415 IdentifierInfo *Platform,
2416 bool Implicit,
2417 VersionTuple Introduced,
2418 VersionTuple Deprecated,
2419 VersionTuple Obsoleted,
2420 bool IsUnavailable,
2421 StringRef Message,
2422 bool IsStrict, StringRef Replacement,
2423 AvailabilityMergeKind AMK,
2424 unsigned AttrSpellingListIndex);
2425 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2426 TypeVisibilityAttr::VisibilityType Vis,
2427 unsigned AttrSpellingListIndex);
2428 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2429 VisibilityAttr::VisibilityType Vis,
2430 unsigned AttrSpellingListIndex);
2431 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2432 unsigned AttrSpellingListIndex, StringRef Uuid);
2433 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2434 unsigned AttrSpellingListIndex);
2435 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2436 unsigned AttrSpellingListIndex);
2437 MSInheritanceAttr *
2438 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2439 unsigned AttrSpellingListIndex,
2440 MSInheritanceAttr::Spelling SemanticSpelling);
2441 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2442 IdentifierInfo *Format, int FormatIdx,
2443 int FirstArg, unsigned AttrSpellingListIndex);
2444 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2445 unsigned AttrSpellingListIndex);
2446 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2447 IdentifierInfo *Ident,
2448 unsigned AttrSpellingListIndex);
2449 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2450 unsigned AttrSpellingListIndex);
2451 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2452 unsigned AttrSpellingListIndex);
2453 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2454 IdentifierInfo *Ident,
2455 unsigned AttrSpellingListIndex);
2456 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2457 unsigned AttrSpellingListIndex);
2458
2459 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2460 AvailabilityMergeKind AMK = AMK_Redeclaration);
2461 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2462 LookupResult &OldDecls);
2463 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2464 bool MergeTypeWithOld);
2465 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2466 Scope *S, bool MergeTypeWithOld);
2467 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2468 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2469 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2470 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2471 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2472 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2473 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2474
2475 // AssignmentAction - This is used by all the assignment diagnostic functions
2476 // to represent what is actually causing the operation
2477 enum AssignmentAction {
2478 AA_Assigning,
2479 AA_Passing,
2480 AA_Returning,
2481 AA_Converting,
2482 AA_Initializing,
2483 AA_Sending,
2484 AA_Casting,
2485 AA_Passing_CFAudited
2486 };
2487
2488 /// C++ Overloading.
2489 enum OverloadKind {
2490 /// This is a legitimate overload: the existing declarations are
2491 /// functions or function templates with different signatures.
2492 Ovl_Overload,
2493
2494 /// This is not an overload because the signature exactly matches
2495 /// an existing declaration.
2496 Ovl_Match,
2497
2498 /// This is not an overload because the lookup results contain a
2499 /// non-function.
2500 Ovl_NonFunction
2501 };
2502 OverloadKind CheckOverload(Scope *S,
2503 FunctionDecl *New,
2504 const LookupResult &OldDecls,
2505 NamedDecl *&OldDecl,
2506 bool IsForUsingDecl);
2507 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2508 bool ConsiderCudaAttrs = true);
2509
2510 /// \brief Checks availability of the function depending on the current
2511 /// function context.Inside an unavailable function,unavailability is ignored.
2512 ///
2513 /// \returns true if \p FD is unavailable and current context is inside
2514 /// an available function, false otherwise.
2515 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2516
2517 ImplicitConversionSequence
2518 TryImplicitConversion(Expr *From, QualType ToType,
2519 bool SuppressUserConversions,
2520 bool AllowExplicit,
2521 bool InOverloadResolution,
2522 bool CStyle,
2523 bool AllowObjCWritebackConversion);
2524
2525 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2526 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2527 bool IsComplexPromotion(QualType FromType, QualType ToType);
2528 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2529 bool InOverloadResolution,
2530 QualType& ConvertedType, bool &IncompatibleObjC);
2531 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2532 QualType& ConvertedType, bool &IncompatibleObjC);
2533 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2534 QualType &ConvertedType);
2535 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2536 QualType& ConvertedType);
2537 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2538 const FunctionProtoType *NewType,
2539 unsigned *ArgPos = nullptr);
2540 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2541 QualType FromType, QualType ToType);
2542
2543 void maybeExtendBlockObject(ExprResult &E);
2544 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2545 bool CheckPointerConversion(Expr *From, QualType ToType,
2546 CastKind &Kind,
2547 CXXCastPath& BasePath,
2548 bool IgnoreBaseAccess,
2549 bool Diagnose = true);
2550 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2551 bool InOverloadResolution,
2552 QualType &ConvertedType);
2553 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2554 CastKind &Kind,
2555 CXXCastPath &BasePath,
2556 bool IgnoreBaseAccess);
2557 bool IsQualificationConversion(QualType FromType, QualType ToType,
2558 bool CStyle, bool &ObjCLifetimeConversion);
2559 bool IsFunctionConversion(QualType FromType, QualType ToType,
2560 QualType &ResultTy);
2561 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2562 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2563
2564 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2565 const VarDecl *NRVOCandidate,
2566 QualType ResultType,
2567 Expr *Value,
2568 bool AllowNRVO = true);
2569
2570 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2571 ExprResult Init);
2572 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2573 SourceLocation EqualLoc,
2574 ExprResult Init,
2575 bool TopLevelOfInitList = false,
2576 bool AllowExplicit = false);
2577 ExprResult PerformObjectArgumentInitialization(Expr *From,
2578 NestedNameSpecifier *Qualifier,
2579 NamedDecl *FoundDecl,
2580 CXXMethodDecl *Method);
2581
2582 ExprResult PerformContextuallyConvertToBool(Expr *From);
2583 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2584
2585 /// Contexts in which a converted constant expression is required.
2586 enum CCEKind {
2587 CCEK_CaseValue, ///< Expression in a case label.
2588 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2589 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2590 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2591 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2592 };
2593 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2594 llvm::APSInt &Value, CCEKind CCE);
2595 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2596 APValue &Value, CCEKind CCE);
2597
2598 /// \brief Abstract base class used to perform a contextual implicit
2599 /// conversion from an expression to any type passing a filter.
2600 class ContextualImplicitConverter {
2601 public:
2602 bool Suppress;
2603 bool SuppressConversion;
2604
2605 ContextualImplicitConverter(bool Suppress = false,
2606 bool SuppressConversion = false)
2607 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2608
2609 /// \brief Determine whether the specified type is a valid destination type
2610 /// for this conversion.
2611 virtual bool match(QualType T) = 0;
2612
2613 /// \brief Emits a diagnostic complaining that the expression does not have
2614 /// integral or enumeration type.
2615 virtual SemaDiagnosticBuilder
2616 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2617
2618 /// \brief Emits a diagnostic when the expression has incomplete class type.
2619 virtual SemaDiagnosticBuilder
2620 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2621
2622 /// \brief Emits a diagnostic when the only matching conversion function
2623 /// is explicit.
2624 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2625 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2626
2627 /// \brief Emits a note for the explicit conversion function.
2628 virtual SemaDiagnosticBuilder
2629 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2630
2631 /// \brief Emits a diagnostic when there are multiple possible conversion
2632 /// functions.
2633 virtual SemaDiagnosticBuilder
2634 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2635
2636 /// \brief Emits a note for one of the candidate conversions.
2637 virtual SemaDiagnosticBuilder
2638 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2639
2640 /// \brief Emits a diagnostic when we picked a conversion function
2641 /// (for cases when we are not allowed to pick a conversion function).
2642 virtual SemaDiagnosticBuilder diagnoseConversion(
2643 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2644
2645 virtual ~ContextualImplicitConverter() {}
2646 };
2647
2648 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2649 bool AllowScopedEnumerations;
2650
2651 public:
2652 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2653 bool Suppress, bool SuppressConversion)
2654 : ContextualImplicitConverter(Suppress, SuppressConversion),
2655 AllowScopedEnumerations(AllowScopedEnumerations) {}
2656
2657 /// Match an integral or (possibly scoped) enumeration type.
2658 bool match(QualType T) override;
2659
2660 SemaDiagnosticBuilder
2661 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2662 return diagnoseNotInt(S, Loc, T);
2663 }
2664
2665 /// \brief Emits a diagnostic complaining that the expression does not have
2666 /// integral or enumeration type.
2667 virtual SemaDiagnosticBuilder
2668 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2669 };
2670
2671 /// Perform a contextual implicit conversion.
2672 ExprResult PerformContextualImplicitConversion(
2673 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2674
2675
2676 enum ObjCSubscriptKind {
2677 OS_Array,
2678 OS_Dictionary,
2679 OS_Error
2680 };
2681 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2682
2683 // Note that LK_String is intentionally after the other literals, as
2684 // this is used for diagnostics logic.
2685 enum ObjCLiteralKind {
2686 LK_Array,
2687 LK_Dictionary,
2688 LK_Numeric,
2689 LK_Boxed,
2690 LK_String,
2691 LK_Block,
2692 LK_None
2693 };
2694 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2695
2696 ExprResult PerformObjectMemberConversion(Expr *From,
2697 NestedNameSpecifier *Qualifier,
2698 NamedDecl *FoundDecl,
2699 NamedDecl *Member);
2700
2701 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2702 // TODO: make this is a typesafe union.
2703 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2704 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2705
2706 void AddOverloadCandidate(FunctionDecl *Function,
2707 DeclAccessPair FoundDecl,
2708 ArrayRef<Expr *> Args,
2709 OverloadCandidateSet &CandidateSet,
2710 bool SuppressUserConversions = false,
2711 bool PartialOverloading = false,
2712 bool AllowExplicit = false,
2713 ConversionSequenceList EarlyConversions = None);
2714 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2715 ArrayRef<Expr *> Args,
2716 OverloadCandidateSet &CandidateSet,
2717 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2718 bool SuppressUserConversions = false,
2719 bool PartialOverloading = false,
2720 bool FirstArgumentIsBase = false);
2721 void AddMethodCandidate(DeclAccessPair FoundDecl,
2722 QualType ObjectType,
2723 Expr::Classification ObjectClassification,
2724 ArrayRef<Expr *> Args,
2725 OverloadCandidateSet& CandidateSet,
2726 bool SuppressUserConversion = false);
2727 void AddMethodCandidate(CXXMethodDecl *Method,
2728 DeclAccessPair FoundDecl,
2729 CXXRecordDecl *ActingContext, QualType ObjectType,
2730 Expr::Classification ObjectClassification,
2731 ArrayRef<Expr *> Args,
2732 OverloadCandidateSet& CandidateSet,
2733 bool SuppressUserConversions = false,
2734 bool PartialOverloading = false,
2735 ConversionSequenceList EarlyConversions = None);
2736 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2737 DeclAccessPair FoundDecl,
2738 CXXRecordDecl *ActingContext,
2739 TemplateArgumentListInfo *ExplicitTemplateArgs,
2740 QualType ObjectType,
2741 Expr::Classification ObjectClassification,
2742 ArrayRef<Expr *> Args,
2743 OverloadCandidateSet& CandidateSet,
2744 bool SuppressUserConversions = false,
2745 bool PartialOverloading = false);
2746 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2747 DeclAccessPair FoundDecl,
2748 TemplateArgumentListInfo *ExplicitTemplateArgs,
2749 ArrayRef<Expr *> Args,
2750 OverloadCandidateSet& CandidateSet,
2751 bool SuppressUserConversions = false,
2752 bool PartialOverloading = false);
2753 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2754 ArrayRef<QualType> ParamTypes,
2755 ArrayRef<Expr *> Args,
2756 OverloadCandidateSet &CandidateSet,
2757 ConversionSequenceList &Conversions,
2758 bool SuppressUserConversions,
2759 CXXRecordDecl *ActingContext = nullptr,
2760 QualType ObjectType = QualType(),
2761 Expr::Classification
2762 ObjectClassification = {});
2763 void AddConversionCandidate(CXXConversionDecl *Conversion,
2764 DeclAccessPair FoundDecl,
2765 CXXRecordDecl *ActingContext,
2766 Expr *From, QualType ToType,
2767 OverloadCandidateSet& CandidateSet,
2768 bool AllowObjCConversionOnExplicit,
2769 bool AllowResultConversion = true);
2770 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2771 DeclAccessPair FoundDecl,
2772 CXXRecordDecl *ActingContext,
2773 Expr *From, QualType ToType,
2774 OverloadCandidateSet &CandidateSet,
2775 bool AllowObjCConversionOnExplicit,
2776 bool AllowResultConversion = true);
2777 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2778 DeclAccessPair FoundDecl,
2779 CXXRecordDecl *ActingContext,
2780 const FunctionProtoType *Proto,
2781 Expr *Object, ArrayRef<Expr *> Args,
2782 OverloadCandidateSet& CandidateSet);
2783 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2784 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2785 OverloadCandidateSet& CandidateSet,
2786 SourceRange OpRange = SourceRange());
2787 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2788 OverloadCandidateSet& CandidateSet,
2789 bool IsAssignmentOperator = false,
2790 unsigned NumContextualBoolArguments = 0);
2791 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2792 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2793 OverloadCandidateSet& CandidateSet);
2794 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2795 SourceLocation Loc,
2796 ArrayRef<Expr *> Args,
2797 TemplateArgumentListInfo *ExplicitTemplateArgs,
2798 OverloadCandidateSet& CandidateSet,
2799 bool PartialOverloading = false);
2800
2801 // Emit as a 'note' the specific overload candidate
2802 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2803 QualType DestType = QualType(),
2804 bool TakingAddress = false);
2805
2806 // Emit as a series of 'note's all template and non-templates identified by
2807 // the expression Expr
2808 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2809 bool TakingAddress = false);
2810
2811 /// Check the enable_if expressions on the given function. Returns the first
2812 /// failing attribute, or NULL if they were all successful.
2813 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2814 bool MissingImplicitThis = false);
2815
2816 /// Find the failed Boolean condition within a given Boolean
2817 /// constant expression, and describe it with a string.
2818 ///
2819 /// \param AllowTopLevelCond Whether to allow the result to be the
2820 /// complete top-level condition.
2821 std::pair<Expr *, std::string>
2822 findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond);
2823
2824 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2825 /// non-ArgDependent DiagnoseIfAttrs.
2826 ///
2827 /// Argument-dependent diagnose_if attributes should be checked each time a
2828 /// function is used as a direct callee of a function call.
2829 ///
2830 /// Returns true if any errors were emitted.
2831 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2832 const Expr *ThisArg,
2833 ArrayRef<const Expr *> Args,
2834 SourceLocation Loc);
2835
2836 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2837 /// ArgDependent DiagnoseIfAttrs.
2838 ///
2839 /// Argument-independent diagnose_if attributes should be checked on every use
2840 /// of a function.
2841 ///
2842 /// Returns true if any errors were emitted.
2843 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2844 SourceLocation Loc);
2845
2846 /// Returns whether the given function's address can be taken or not,
2847 /// optionally emitting a diagnostic if the address can't be taken.
2848 ///
2849 /// Returns false if taking the address of the function is illegal.
2850 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2851 bool Complain = false,
2852 SourceLocation Loc = SourceLocation());
2853
2854 // [PossiblyAFunctionType] --> [Return]
2855 // NonFunctionType --> NonFunctionType
2856 // R (A) --> R(A)
2857 // R (*)(A) --> R (A)
2858 // R (&)(A) --> R (A)
2859 // R (S::*)(A) --> R (A)
2860 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2861
2862 FunctionDecl *
2863 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2864 QualType TargetType,
2865 bool Complain,
2866 DeclAccessPair &Found,
2867 bool *pHadMultipleCandidates = nullptr);
2868
2869 FunctionDecl *
2870 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2871 DeclAccessPair &FoundResult);
2872
2873 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2874 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2875
2876 FunctionDecl *
2877 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2878 bool Complain = false,
2879 DeclAccessPair *Found = nullptr);
2880
2881 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2882 ExprResult &SrcExpr,
2883 bool DoFunctionPointerConverion = false,
2884 bool Complain = false,
2885 SourceRange OpRangeForComplaining = SourceRange(),
2886 QualType DestTypeForComplaining = QualType(),
2887 unsigned DiagIDForComplaining = 0);
2888
2889
2890 Expr *FixOverloadedFunctionReference(Expr *E,
2891 DeclAccessPair FoundDecl,
2892 FunctionDecl *Fn);
2893 ExprResult FixOverloadedFunctionReference(ExprResult,
2894 DeclAccessPair FoundDecl,
2895 FunctionDecl *Fn);
2896
2897 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2898 ArrayRef<Expr *> Args,
2899 OverloadCandidateSet &CandidateSet,
2900 bool PartialOverloading = false);
2901
2902 // An enum used to represent the different possible results of building a
2903 // range-based for loop.
2904 enum ForRangeStatus {
2905 FRS_Success,
2906 FRS_NoViableFunction,
2907 FRS_DiagnosticIssued
2908 };
2909
2910 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2911 SourceLocation RangeLoc,
2912 const DeclarationNameInfo &NameInfo,
2913 LookupResult &MemberLookup,
2914 OverloadCandidateSet *CandidateSet,
2915 Expr *Range, ExprResult *CallExpr);
2916
2917 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2918 UnresolvedLookupExpr *ULE,
2919 SourceLocation LParenLoc,
2920 MultiExprArg Args,
2921 SourceLocation RParenLoc,
2922 Expr *ExecConfig,
2923 bool AllowTypoCorrection=true,
2924 bool CalleesAddressIsTaken=false);
2925
2926 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2927 MultiExprArg Args, SourceLocation RParenLoc,
2928 OverloadCandidateSet *CandidateSet,
2929 ExprResult *Result);
2930
2931 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2932 UnaryOperatorKind Opc,
2933 const UnresolvedSetImpl &Fns,
2934 Expr *input, bool RequiresADL = true);
2935
2936 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2937 BinaryOperatorKind Opc,
2938 const UnresolvedSetImpl &Fns,
2939 Expr *LHS, Expr *RHS,
2940 bool RequiresADL = true);
2941
2942 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2943 SourceLocation RLoc,
2944 Expr *Base,Expr *Idx);
2945
2946 ExprResult
2947 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2948 SourceLocation LParenLoc,
2949 MultiExprArg Args,
2950 SourceLocation RParenLoc);
2951 ExprResult
2952 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2953 MultiExprArg Args,
2954 SourceLocation RParenLoc);
2955
2956 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2957 SourceLocation OpLoc,
2958 bool *NoArrowOperatorFound = nullptr);
2959
2960 /// CheckCallReturnType - Checks that a call expression's return type is
2961 /// complete. Returns true on failure. The location passed in is the location
2962 /// that best represents the call.
2963 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2964 CallExpr *CE, FunctionDecl *FD);
2965
2966 /// Helpers for dealing with blocks and functions.
2967 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2968 bool CheckParameterNames);
2969 void CheckCXXDefaultArguments(FunctionDecl *FD);
2970 void CheckExtraCXXDefaultArguments(Declarator &D);
2971 Scope *getNonFieldDeclScope(Scope *S);
2972
2973 /// \name Name lookup
2974 ///
2975 /// These routines provide name lookup that is used during semantic
2976 /// analysis to resolve the various kinds of names (identifiers,
2977 /// overloaded operator names, constructor names, etc.) into zero or
2978 /// more declarations within a particular scope. The major entry
2979 /// points are LookupName, which performs unqualified name lookup,
2980 /// and LookupQualifiedName, which performs qualified name lookup.
2981 ///
2982 /// All name lookup is performed based on some specific criteria,
2983 /// which specify what names will be visible to name lookup and how
2984 /// far name lookup should work. These criteria are important both
2985 /// for capturing language semantics (certain lookups will ignore
2986 /// certain names, for example) and for performance, since name
2987 /// lookup is often a bottleneck in the compilation of C++. Name
2988 /// lookup criteria is specified via the LookupCriteria enumeration.
2989 ///
2990 /// The results of name lookup can vary based on the kind of name
2991 /// lookup performed, the current language, and the translation
2992 /// unit. In C, for example, name lookup will either return nothing
2993 /// (no entity found) or a single declaration. In C++, name lookup
2994 /// can additionally refer to a set of overloaded functions or
2995 /// result in an ambiguity. All of the possible results of name
2996 /// lookup are captured by the LookupResult class, which provides
2997 /// the ability to distinguish among them.
2998 //@{
2999
3000 /// @brief Describes the kind of name lookup to perform.
3001 enum LookupNameKind {
3002 /// Ordinary name lookup, which finds ordinary names (functions,
3003 /// variables, typedefs, etc.) in C and most kinds of names
3004 /// (functions, variables, members, types, etc.) in C++.
3005 LookupOrdinaryName = 0,
3006 /// Tag name lookup, which finds the names of enums, classes,
3007 /// structs, and unions.
3008 LookupTagName,
3009 /// Label name lookup.
3010 LookupLabel,
3011 /// Member name lookup, which finds the names of
3012 /// class/struct/union members.
3013 LookupMemberName,
3014 /// Look up of an operator name (e.g., operator+) for use with
3015 /// operator overloading. This lookup is similar to ordinary name
3016 /// lookup, but will ignore any declarations that are class members.
3017 LookupOperatorName,
3018 /// Look up of a name that precedes the '::' scope resolution
3019 /// operator in C++. This lookup completely ignores operator, object,
3020 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3021 LookupNestedNameSpecifierName,
3022 /// Look up a namespace name within a C++ using directive or
3023 /// namespace alias definition, ignoring non-namespace names (C++
3024 /// [basic.lookup.udir]p1).
3025 LookupNamespaceName,
3026 /// Look up all declarations in a scope with the given name,
3027 /// including resolved using declarations. This is appropriate
3028 /// for checking redeclarations for a using declaration.
3029 LookupUsingDeclName,
3030 /// Look up an ordinary name that is going to be redeclared as a
3031 /// name with linkage. This lookup ignores any declarations that
3032 /// are outside of the current scope unless they have linkage. See
3033 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3034 LookupRedeclarationWithLinkage,
3035 /// Look up a friend of a local class. This lookup does not look
3036 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3037 LookupLocalFriendName,
3038 /// Look up the name of an Objective-C protocol.
3039 LookupObjCProtocolName,
3040 /// Look up implicit 'self' parameter of an objective-c method.
3041 LookupObjCImplicitSelfParam,
3042 /// \brief Look up the name of an OpenMP user-defined reduction operation.
3043 LookupOMPReductionName,
3044 /// \brief Look up any declaration with any name.
3045 LookupAnyName
3046 };
3047
3048 /// \brief Specifies whether (or how) name lookup is being performed for a
3049 /// redeclaration (vs. a reference).
3050 enum RedeclarationKind {
3051 /// \brief The lookup is a reference to this name that is not for the
3052 /// purpose of redeclaring the name.
3053 NotForRedeclaration = 0,
3054 /// \brief The lookup results will be used for redeclaration of a name,
3055 /// if an entity by that name already exists and is visible.
3056 ForVisibleRedeclaration,
3057 /// \brief The lookup results will be used for redeclaration of a name
3058 /// with external linkage; non-visible lookup results with external linkage
3059 /// may also be found.
3060 ForExternalRedeclaration
3061 };
3062
3063 RedeclarationKind forRedeclarationInCurContext() {
3064 // A declaration with an owning module for linkage can never link against
3065 // anything that is not visible. We don't need to check linkage here; if
3066 // the context has internal linkage, redeclaration lookup won't find things
3067 // from other TUs, and we can't safely compute linkage yet in general.
3068 if (cast<Decl>(CurContext)
3069 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3070 return ForVisibleRedeclaration;
3071 return ForExternalRedeclaration;
3072 }
3073
3074 /// \brief The possible outcomes of name lookup for a literal operator.
3075 enum LiteralOperatorLookupResult {
3076 /// \brief The lookup resulted in an error.
3077 LOLR_Error,
3078 /// \brief The lookup found no match but no diagnostic was issued.
3079 LOLR_ErrorNoDiagnostic,
3080 /// \brief The lookup found a single 'cooked' literal operator, which
3081 /// expects a normal literal to be built and passed to it.
3082 LOLR_Cooked,
3083 /// \brief The lookup found a single 'raw' literal operator, which expects
3084 /// a string literal containing the spelling of the literal token.
3085 LOLR_Raw,
3086 /// \brief The lookup found an overload set of literal operator templates,
3087 /// which expect the characters of the spelling of the literal token to be
3088 /// passed as a non-type template argument pack.
3089 LOLR_Template,
3090 /// \brief The lookup found an overload set of literal operator templates,
3091 /// which expect the character type and characters of the spelling of the
3092 /// string literal token to be passed as template arguments.
3093 LOLR_StringTemplate
3094 };
3095
3096 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3097 CXXSpecialMember SM,
3098 bool ConstArg,
3099 bool VolatileArg,
3100 bool RValueThis,
3101 bool ConstThis,
3102 bool VolatileThis);
3103
3104 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3105 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3106 TypoRecoveryCallback;
3107
3108private:
3109 bool CppLookupName(LookupResult &R, Scope *S);
3110
3111 struct TypoExprState {
3112 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3113 TypoDiagnosticGenerator DiagHandler;
3114 TypoRecoveryCallback RecoveryHandler;
3115 TypoExprState();
3116 TypoExprState(TypoExprState &&other) noexcept;
3117 TypoExprState &operator=(TypoExprState &&other) noexcept;
3118 };
3119
3120 /// \brief The set of unhandled TypoExprs and their associated state.
3121 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3122
3123 /// \brief Creates a new TypoExpr AST node.
3124 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3125 TypoDiagnosticGenerator TDG,
3126 TypoRecoveryCallback TRC);
3127
3128 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3129 //
3130 // The boolean value will be true to indicate that the namespace was loaded
3131 // from an AST/PCH file, or false otherwise.
3132 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3133
3134 /// \brief Whether we have already loaded known namespaces from an extenal
3135 /// source.
3136 bool LoadedExternalKnownNamespaces;
3137
3138 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3139 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3140 /// should be skipped entirely.
3141 std::unique_ptr<TypoCorrectionConsumer>
3142 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3143 Sema::LookupNameKind LookupKind, Scope *S,
3144 CXXScopeSpec *SS,
3145 std::unique_ptr<CorrectionCandidateCallback> CCC,
3146 DeclContext *MemberContext, bool EnteringContext,
3147 const ObjCObjectPointerType *OPT,
3148 bool ErrorRecovery);
3149
3150public:
3151 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3152
3153 /// \brief Clears the state of the given TypoExpr.
3154 void clearDelayedTypo(TypoExpr *TE);
3155
3156 /// \brief Look up a name, looking for a single declaration. Return
3157 /// null if the results were absent, ambiguous, or overloaded.
3158 ///
3159 /// It is preferable to use the elaborated form and explicitly handle
3160 /// ambiguity and overloaded.
3161 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3162 SourceLocation Loc,
3163 LookupNameKind NameKind,
3164 RedeclarationKind Redecl
3165 = NotForRedeclaration);
3166 bool LookupName(LookupResult &R, Scope *S,
3167 bool AllowBuiltinCreation = false);
3168 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3169 bool InUnqualifiedLookup = false);
3170 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3171 CXXScopeSpec &SS);
3172 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3173 bool AllowBuiltinCreation = false,
3174 bool EnteringContext = false);
3175 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3176 RedeclarationKind Redecl
3177 = NotForRedeclaration);
3178 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3179
3180 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3181 QualType T1, QualType T2,
3182 UnresolvedSetImpl &Functions);
3183
3184 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3185 SourceLocation GnuLabelLoc = SourceLocation());
3186
3187 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3188 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3189 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3190 unsigned Quals);
3191 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3192 bool RValueThis, unsigned ThisQuals);
3193 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3194 unsigned Quals);
3195 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3196 bool RValueThis, unsigned ThisQuals);
3197 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3198
3199 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3200 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3201 ArrayRef<QualType> ArgTys,
3202 bool AllowRaw,
3203 bool AllowTemplate,
3204 bool AllowStringTemplate,
3205 bool DiagnoseMissing);
3206 bool isKnownName(StringRef name);
3207
3208 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3209 ArrayRef<Expr *> Args, ADLResult &Functions);
3210
3211 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3212 VisibleDeclConsumer &Consumer,
3213 bool IncludeGlobalScope = true,
3214 bool LoadExternal = true);
3215 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3216 VisibleDeclConsumer &Consumer,
3217 bool IncludeGlobalScope = true,
3218 bool IncludeDependentBases = false,
3219 bool LoadExternal = true);
3220
3221 enum CorrectTypoKind {
3222 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3223 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3224 };
3225
3226 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3227 Sema::LookupNameKind LookupKind,
3228 Scope *S, CXXScopeSpec *SS,
3229 std::unique_ptr<CorrectionCandidateCallback> CCC,
3230 CorrectTypoKind Mode,
3231 DeclContext *MemberContext = nullptr,
3232 bool EnteringContext = false,
3233 const ObjCObjectPointerType *OPT = nullptr,
3234 bool RecordFailure = true);
3235
3236 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3237 Sema::LookupNameKind LookupKind, Scope *S,
3238 CXXScopeSpec *SS,
3239 std::unique_ptr<CorrectionCandidateCallback> CCC,
3240 TypoDiagnosticGenerator TDG,
3241 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3242 DeclContext *MemberContext = nullptr,
3243 bool EnteringContext = false,
3244 const ObjCObjectPointerType *OPT = nullptr);
3245
3246 /// \brief Process any TypoExprs in the given Expr and its children,
3247 /// generating diagnostics as appropriate and returning a new Expr if there
3248 /// were typos that were all successfully corrected and ExprError if one or
3249 /// more typos could not be corrected.
3250 ///
3251 /// \param E The Expr to check for TypoExprs.
3252 ///
3253 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3254 /// initializer.
3255 ///
3256 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3257 /// it is an acceptable/usable result from a single combination of typo
3258 /// corrections. As long as the filter returns ExprError, different
3259 /// combinations of corrections will be tried until all are exhausted.
3260 ExprResult
3261 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3262 llvm::function_ref<ExprResult(Expr *)> Filter =
3263 [](Expr *E) -> ExprResult { return E; });
3264
3265 ExprResult
3266 CorrectDelayedTyposInExpr(Expr *E,
3267 llvm::function_ref<ExprResult(Expr *)> Filter) {
3268 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3269 }
3270
3271 ExprResult
3272 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3273 llvm::function_ref<ExprResult(Expr *)> Filter =
3274 [](Expr *E) -> ExprResult { return E; }) {
3275 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3276 }
3277
3278 ExprResult
3279 CorrectDelayedTyposInExpr(ExprResult ER,
3280 llvm::function_ref<ExprResult(Expr *)> Filter) {
3281 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3282 }
3283
3284 void diagnoseTypo(const TypoCorrection &Correction,
3285 const PartialDiagnostic &TypoDiag,
3286 bool ErrorRecovery = true);
3287
3288 void diagnoseTypo(const TypoCorrection &Correction,
3289 const PartialDiagnostic &TypoDiag,
3290 const PartialDiagnostic &PrevNote,
3291 bool ErrorRecovery = true);
3292
3293 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3294
3295 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3296 ArrayRef<Expr *> Args,
3297 AssociatedNamespaceSet &AssociatedNamespaces,
3298 AssociatedClassSet &AssociatedClasses);
3299
3300 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3301 bool ConsiderLinkage, bool AllowInlineNamespace);
3302
3303 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3304
3305 void DiagnoseAmbiguousLookup(LookupResult &Result);
3306 //@}
3307
3308 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3309 SourceLocation IdLoc,
3310 bool TypoCorrection = false);
3311 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3312 Scope *S, bool ForRedeclaration,
3313 SourceLocation Loc);
3314 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3315 Scope *S);
3316 void AddKnownFunctionAttributes(FunctionDecl *FD);
3317
3318 // More parsing and symbol table subroutines.
3319
3320 void ProcessPragmaWeak(Scope *S, Decl *D);
3321 // Decl attributes - this routine is the top level dispatcher.
3322 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3323 // Helper for delayed processing of attributes.
3324 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3325 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3326 bool IncludeCXX11Attributes = true);
3327 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3328 const AttributeList *AttrList);
3329
3330 void checkUnusedDeclAttributes(Declarator &D);
3331
3332 /// Determine if type T is a valid subject for a nonnull and similar
3333 /// attributes. By default, we look through references (the behavior used by
3334 /// nonnull), but if the second parameter is true, then we treat a reference
3335 /// type as valid.
3336 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3337
3338 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3339 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3340 const FunctionDecl *FD = nullptr);
3341 bool CheckNoReturnAttr(const AttributeList &attr);
3342 bool CheckNoCallerSavedRegsAttr(const AttributeList &attr);
3343 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3344 unsigned ArgNum, StringRef &Str,
3345 SourceLocation *ArgLocation = nullptr);
3346 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3347 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3348 bool checkMSInheritanceAttrOnDefinition(
3349 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3350 MSInheritanceAttr::Spelling SemanticSpelling);
3351
3352 void CheckAlignasUnderalignment(Decl *D);
3353
3354 /// Adjust the calling convention of a method to be the ABI default if it
3355 /// wasn't specified explicitly. This handles method types formed from
3356 /// function type typedefs and typename template arguments.
3357 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3358 SourceLocation Loc);
3359
3360 // Check if there is an explicit attribute, but only look through parens.
3361 // The intent is to look for an attribute on the current declarator, but not
3362 // one that came from a typedef.
3363 bool hasExplicitCallingConv(QualType &T);
3364
3365 /// Get the outermost AttributedType node that sets a calling convention.
3366 /// Valid types should not have multiple attributes with different CCs.
3367 const AttributedType *getCallingConvAttributedType(QualType T) const;
3368
3369 /// Check whether a nullability type specifier can be added to the given
3370 /// type.
3371 ///
3372 /// \param type The type to which the nullability specifier will be
3373 /// added. On success, this type will be updated appropriately.
3374 ///
3375 /// \param nullability The nullability specifier to add.
3376 ///
3377 /// \param nullabilityLoc The location of the nullability specifier.
3378 ///
3379 /// \param isContextSensitive Whether this nullability specifier was
3380 /// written as a context-sensitive keyword (in an Objective-C
3381 /// method) or an Objective-C property attribute, rather than as an
3382 /// underscored type specifier.
3383 ///
3384 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3385 /// array type (e.g., because it will decay to a pointer).
3386 ///
3387 /// \returns true if nullability cannot be applied, false otherwise.
3388 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3389 SourceLocation nullabilityLoc,
3390 bool isContextSensitive,
3391 bool allowArrayTypes);
3392
3393 /// \brief Stmt attributes - this routine is the top level dispatcher.
3394 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3395 SourceRange Range);
3396
3397 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3398 ObjCMethodDecl *MethodDecl,
3399 bool IsProtocolMethodDecl);
3400
3401 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3402 ObjCMethodDecl *Overridden,
3403 bool IsProtocolMethodDecl);
3404
3405 /// WarnExactTypedMethods - This routine issues a warning if method
3406 /// implementation declaration matches exactly that of its declaration.
3407 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3408 ObjCMethodDecl *MethodDecl,
3409 bool IsProtocolMethodDecl);
3410
3411 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3412
3413 /// CheckImplementationIvars - This routine checks if the instance variables
3414 /// listed in the implelementation match those listed in the interface.
3415 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3416 ObjCIvarDecl **Fields, unsigned nIvars,
3417 SourceLocation Loc);
3418
3419 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3420 /// remains unimplemented in the class or category \@implementation.
3421 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3422 ObjCContainerDecl* IDecl,
3423 bool IncompleteImpl = false);
3424
3425 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3426 /// which must be implemented by this implementation.
3427 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3428 ObjCContainerDecl *CDecl,
3429 bool SynthesizeProperties);
3430
3431 /// Diagnose any null-resettable synthesized setters.
3432 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3433
3434 /// DefaultSynthesizeProperties - This routine default synthesizes all
3435 /// properties which must be synthesized in the class's \@implementation.
3436 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3437 ObjCInterfaceDecl *IDecl,
3438 SourceLocation AtEnd);
3439 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3440
3441 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3442 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3443 /// declared in class 'IFace'.
3444 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3445 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3446
3447 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3448 /// backs the property is not used in the property's accessor.
3449 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3450 const ObjCImplementationDecl *ImplD);
3451
3452 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3453 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3454 /// It also returns ivar's property on success.
3455 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3456 const ObjCPropertyDecl *&PDecl) const;
3457
3458 /// Called by ActOnProperty to handle \@property declarations in
3459 /// class extensions.
3460 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3461 SourceLocation AtLoc,
3462 SourceLocation LParenLoc,
3463 FieldDeclarator &FD,
3464 Selector GetterSel,
3465 SourceLocation GetterNameLoc,
3466 Selector SetterSel,
3467 SourceLocation SetterNameLoc,
3468 const bool isReadWrite,
3469 unsigned &Attributes,
3470 const unsigned AttributesAsWritten,
3471 QualType T,
3472 TypeSourceInfo *TSI,
3473 tok::ObjCKeywordKind MethodImplKind);
3474
3475 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3476 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3477 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3478 ObjCContainerDecl *CDecl,
3479 SourceLocation AtLoc,
3480 SourceLocation LParenLoc,
3481 FieldDeclarator &FD,
3482 Selector GetterSel,
3483 SourceLocation GetterNameLoc,
3484 Selector SetterSel,
3485 SourceLocation SetterNameLoc,
3486 const bool isReadWrite,
3487 const unsigned Attributes,
3488 const unsigned AttributesAsWritten,
3489 QualType T,
3490 TypeSourceInfo *TSI,
3491 tok::ObjCKeywordKind MethodImplKind,
3492 DeclContext *lexicalDC = nullptr);
3493
3494 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3495 /// warning) when atomic property has one but not the other user-declared
3496 /// setter or getter.
3497 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3498 ObjCInterfaceDecl* IDecl);
3499
3500 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3501
3502 void DiagnoseMissingDesignatedInitOverrides(
3503 const ObjCImplementationDecl *ImplD,
3504 const ObjCInterfaceDecl *IFD);
3505
3506 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3507
3508 enum MethodMatchStrategy {
3509 MMS_loose,
3510 MMS_strict
3511 };
3512
3513 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3514 /// true, or false, accordingly.
3515 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3516 const ObjCMethodDecl *PrevMethod,
3517 MethodMatchStrategy strategy = MMS_strict);
3518
3519 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3520 /// or protocol against those declared in their implementations.
3521 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3522 const SelectorSet &ClsMap,
3523 SelectorSet &InsMapSeen,
3524 SelectorSet &ClsMapSeen,
3525 ObjCImplDecl* IMPDecl,
3526 ObjCContainerDecl* IDecl,
3527 bool &IncompleteImpl,
3528 bool ImmediateClass,
3529 bool WarnCategoryMethodImpl=false);
3530
3531 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3532 /// category matches with those implemented in its primary class and
3533 /// warns each time an exact match is found.
3534 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3535
3536 /// \brief Add the given method to the list of globally-known methods.
3537 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3538
3539private:
3540 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3541 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3542 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3543
3544 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3545 /// optionally warns if there are multiple signatures.
3546 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3547 bool receiverIdOrClass,
3548 bool instance);
3549
3550public:
3551 /// \brief - Returns instance or factory methods in global method pool for
3552 /// given selector. It checks the desired kind first, if none is found, and
3553 /// parameter checkTheOther is set, it then checks the other kind. If no such
3554 /// method or only one method is found, function returns false; otherwise, it
3555 /// returns true.
3556 bool
3557 CollectMultipleMethodsInGlobalPool(Selector Sel,
3558 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3559 bool InstanceFirst, bool CheckTheOther,
3560 const ObjCObjectType *TypeBound = nullptr);
3561
3562 bool
3563 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3564 SourceRange R, bool receiverIdOrClass,
3565 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3566
3567 void
3568 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3569 Selector Sel, SourceRange R,
3570 bool receiverIdOrClass);
3571
3572private:
3573 /// \brief - Returns a selector which best matches given argument list or
3574 /// nullptr if none could be found
3575 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3576 bool IsInstance,
3577 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3578
3579
3580 /// \brief Record the typo correction failure and return an empty correction.
3581 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3582 bool RecordFailure = true) {
3583 if (RecordFailure)
3584 TypoCorrectionFailures[Typo].insert(TypoLoc);
3585 return TypoCorrection();
3586 }
3587
3588public:
3589 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3590 /// unit are added to a global pool. This allows us to efficiently associate
3591 /// a selector with a method declaraation for purposes of typechecking
3592 /// messages sent to "id" (where the class of the object is unknown).
3593 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3594 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3595 }
3596
3597 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3598 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3599 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3600 }
3601
3602 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3603 /// pool.
3604 void AddAnyMethodToGlobalPool(Decl *D);
3605
3606 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3607 /// there are multiple signatures.
3608 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3609 bool receiverIdOrClass=false) {
3610 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3611 /*instance*/true);
3612 }
3613
3614 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3615 /// there are multiple signatures.
3616 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3617 bool receiverIdOrClass=false) {
3618 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3619 /*instance*/false);
3620 }
3621
3622 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3623 QualType ObjectType=QualType());
3624 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3625 /// implementation.
3626 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3627
3628 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3629 /// initialization.
3630 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3631 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3632
3633 //===--------------------------------------------------------------------===//
3634 // Statement Parsing Callbacks: SemaStmt.cpp.
3635public:
3636 class FullExprArg {
3637 public:
3638 FullExprArg() : E(nullptr) { }
3639 FullExprArg(Sema &actions) : E(nullptr) { }
3640
3641 ExprResult release() {
3642 return E;
3643 }
3644
3645 Expr *get() const { return E; }
3646
3647 Expr *operator->() {
3648 return E;
3649 }
3650
3651 private:
3652 // FIXME: No need to make the entire Sema class a friend when it's just
3653 // Sema::MakeFullExpr that needs access to the constructor below.
3654 friend class Sema;
3655
3656 explicit FullExprArg(Expr *expr) : E(expr) {}
3657
3658 Expr *E;
3659 };
3660
3661 FullExprArg MakeFullExpr(Expr *Arg) {
3662 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3663 }
3664 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3665 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3666 }
3667 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3668 ExprResult FE =
3669 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3670 /*DiscardedValue*/ true);
3671 return FullExprArg(FE.get());
3672 }
3673
3674 StmtResult ActOnExprStmt(ExprResult Arg);
3675 StmtResult ActOnExprStmtError();
3676
3677 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3678 bool HasLeadingEmptyMacro = false);
3679
3680 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3681 void ActOnFinishOfCompoundStmt();
3682 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3683 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3684
3685 /// \brief A RAII object to enter scope of a compound statement.
3686 class CompoundScopeRAII {
3687 public:
3688 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3689 S.ActOnStartOfCompoundStmt(IsStmtExpr);
3690 }
3691
3692 ~CompoundScopeRAII() {
3693 S.ActOnFinishOfCompoundStmt();
3694 }
3695
3696 private:
3697 Sema &S;
3698 };
3699
3700 /// An RAII helper that pops function a function scope on exit.
3701 struct FunctionScopeRAII {
3702 Sema &S;
3703 bool Active;
3704 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3705 ~FunctionScopeRAII() {
3706 if (Active)
3707 S.PopFunctionScopeInfo();
3708 }
3709 void disable() { Active = false; }
3710 };
3711
3712 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3713 SourceLocation StartLoc,
3714 SourceLocation EndLoc);
3715 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3716 StmtResult ActOnForEachLValueExpr(Expr *E);
3717 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3718 SourceLocation DotDotDotLoc, Expr *RHSVal,
3719 SourceLocation ColonLoc);
3720 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3721
3722 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3723 SourceLocation ColonLoc,
3724 Stmt *SubStmt, Scope *CurScope);
3725 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3726 SourceLocation ColonLoc, Stmt *SubStmt);
3727
3728 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3729 ArrayRef<const Attr*> Attrs,
3730 Stmt *SubStmt);
3731
3732 class ConditionResult;
3733 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3734 Stmt *InitStmt,
3735 ConditionResult Cond, Stmt *ThenVal,
3736 SourceLocation ElseLoc, Stmt *ElseVal);
3737 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3738 Stmt *InitStmt,
3739 ConditionResult Cond, Stmt *ThenVal,
3740 SourceLocation ElseLoc, Stmt *ElseVal);
3741 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3742 Stmt *InitStmt,
3743 ConditionResult Cond);
3744 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3745 Stmt *Switch, Stmt *Body);
3746 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3747 Stmt *Body);
3748 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3749 SourceLocation WhileLoc, SourceLocation CondLParen,
3750 Expr *Cond, SourceLocation CondRParen);
3751
3752 StmtResult ActOnForStmt(SourceLocation ForLoc,
3753 SourceLocation LParenLoc,
3754 Stmt *First,
3755 ConditionResult Second,
3756 FullExprArg Third,
3757 SourceLocation RParenLoc,
3758 Stmt *Body);
3759 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3760 Expr *collection);
3761 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3762 Stmt *First, Expr *collection,
3763 SourceLocation RParenLoc);
3764 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3765
3766 enum BuildForRangeKind {
3767 /// Initial building of a for-range statement.
3768 BFRK_Build,
3769 /// Instantiation or recovery rebuild of a for-range statement. Don't
3770 /// attempt any typo-correction.
3771 BFRK_Rebuild,
3772 /// Determining whether a for-range statement could be built. Avoid any
3773 /// unnecessary or irreversible actions.
3774 BFRK_Check
3775 };
3776
3777 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3778 SourceLocation CoawaitLoc,
3779 Stmt *LoopVar,
3780 SourceLocation ColonLoc, Expr *Collection,
3781 SourceLocation RParenLoc,
3782 BuildForRangeKind Kind);
3783 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3784 SourceLocation CoawaitLoc,
3785 SourceLocation ColonLoc,
3786 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3787 Expr *Cond, Expr *Inc,
3788 Stmt *LoopVarDecl,
3789 SourceLocation RParenLoc,
3790 BuildForRangeKind Kind);
3791 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3792
3793 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3794 SourceLocation LabelLoc,
3795 LabelDecl *TheDecl);
3796 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3797 SourceLocation StarLoc,
3798 Expr *DestExp);
3799 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3800 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3801
3802 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3803 CapturedRegionKind Kind, unsigned NumParams);
3804 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3805 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3806 CapturedRegionKind Kind,
3807 ArrayRef<CapturedParamNameType> Params);
3808 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3809 void ActOnCapturedRegionError();
3810 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3811 SourceLocation Loc,
3812 unsigned NumParams);
3813 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3814 bool AllowParamOrMoveConstructible);
3815 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3816 bool AllowParamOrMoveConstructible);
3817
3818 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3819 Scope *CurScope);
3820 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3821 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3822
3823 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3824 bool IsVolatile, unsigned NumOutputs,
3825 unsigned NumInputs, IdentifierInfo **Names,
3826 MultiExprArg Constraints, MultiExprArg Exprs,
3827 Expr *AsmString, MultiExprArg Clobbers,
3828 SourceLocation RParenLoc);
3829
3830 void FillInlineAsmIdentifierInfo(Expr *Res,
3831 llvm::InlineAsmIdentifierInfo &Info);
3832 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3833 SourceLocation TemplateKWLoc,
3834 UnqualifiedId &Id,
3835 bool IsUnevaluatedContext);
3836 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3837 unsigned &Offset, SourceLocation AsmLoc);
3838 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3839 SourceLocation AsmLoc);
3840 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3841 ArrayRef<Token> AsmToks,
3842 StringRef AsmString,
3843 unsigned NumOutputs, unsigned NumInputs,
3844 ArrayRef<StringRef> Constraints,
3845 ArrayRef<StringRef> Clobbers,
3846 ArrayRef<Expr*> Exprs,
3847 SourceLocation EndLoc);
3848 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3849 SourceLocation Location,
3850 bool AlwaysCreate);
3851
3852 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3853 SourceLocation StartLoc,
3854 SourceLocation IdLoc, IdentifierInfo *Id,
3855 bool Invalid = false);
3856
3857 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3858
3859 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3860 Decl *Parm, Stmt *Body);
3861
3862 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3863
3864 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3865 MultiStmtArg Catch, Stmt *Finally);
3866
3867 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3868 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3869 Scope *CurScope);
3870 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3871 Expr *operand);
3872 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3873 Expr *SynchExpr,
3874 Stmt *SynchBody);
3875
3876 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3877
3878 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3879 SourceLocation StartLoc,
3880 SourceLocation IdLoc,
3881 IdentifierInfo *Id);
3882
3883 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3884
3885 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3886 Decl *ExDecl, Stmt *HandlerBlock);
3887 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3888 ArrayRef<Stmt *> Handlers);
3889
3890 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3891 SourceLocation TryLoc, Stmt *TryBlock,
3892 Stmt *Handler);
3893 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3894 Expr *FilterExpr,
3895 Stmt *Block);
3896 void ActOnStartSEHFinallyBlock();
3897 void ActOnAbortSEHFinallyBlock();
3898 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3899 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3900
3901 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3902
3903 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3904
3905 /// \brief If it's a file scoped decl that must warn if not used, keep track
3906 /// of it.
3907 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3908
3909 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3910 /// whose result is unused, warn.
3911 void DiagnoseUnusedExprResult(const Stmt *S);
3912 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3913 void DiagnoseUnusedDecl(const NamedDecl *ND);
3914
3915 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3916 /// statement as a \p Body, and it is located on the same line.
3917 ///
3918 /// This helps prevent bugs due to typos, such as:
3919 /// if (condition);
3920 /// do_stuff();
3921 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3922 const Stmt *Body,
3923 unsigned DiagID);
3924
3925 /// Warn if a for/while loop statement \p S, which is followed by
3926 /// \p PossibleBody, has a suspicious null statement as a body.
3927 void DiagnoseEmptyLoopBody(const Stmt *S,
3928 const Stmt *PossibleBody);
3929
3930 /// Warn if a value is moved to itself.
3931 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3932 SourceLocation OpLoc);
3933
3934 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3935 /// _Nonnull one.
3936 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3937 SourceLocation Loc);
3938
3939 /// Warn when implicitly casting 0 to nullptr.
3940 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3941
3942 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3943 return DelayedDiagnostics.push(pool);
3944 }
3945 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3946
3947 typedef ProcessingContextState ParsingClassState;
3948 ParsingClassState PushParsingClass() {
3949 return DelayedDiagnostics.pushUndelayed();
3950 }
3951 void PopParsingClass(ParsingClassState state) {
3952 DelayedDiagnostics.popUndelayed(state);
3953 }
3954
3955 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3956
3957 void DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
3958 const ObjCInterfaceDecl *UnknownObjCClass,
3959 bool ObjCPropertyAccess,
3960 bool AvoidPartialAvailabilityChecks = false);
3961
3962 bool makeUnavailableInSystemHeader(SourceLocation loc,
3963 UnavailableAttr::ImplicitReason reason);
3964
3965 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3966 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3967
3968 //===--------------------------------------------------------------------===//
3969 // Expression Parsing Callbacks: SemaExpr.cpp.
3970
3971 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3972 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3973 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
3974 bool ObjCPropertyAccess = false,
3975 bool AvoidPartialAvailabilityChecks = false);
3976 void NoteDeletedFunction(FunctionDecl *FD);
3977 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3978 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3979 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3980 ObjCMethodDecl *Getter,
3981 SourceLocation Loc);
3982 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3983 ArrayRef<Expr *> Args);
3984
3985 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3986 Decl *LambdaContextDecl = nullptr,
3987 bool IsDecltype = false);
3988 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3989 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3990 ReuseLambdaContextDecl_t,
3991 bool IsDecltype = false);
3992 void PopExpressionEvaluationContext();
3993
3994 void DiscardCleanupsInEvaluationContext();
3995
3996 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3997 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3998
3999 ExprResult ActOnConstantExpression(ExprResult Res);
4000
4001 // Functions for marking a declaration referenced. These functions also
4002 // contain the relevant logic for marking if a reference to a function or
4003 // variable is an odr-use (in the C++11 sense). There are separate variants
4004 // for expressions referring to a decl; these exist because odr-use marking
4005 // needs to be delayed for some constant variables when we build one of the
4006 // named expressions.
4007 //
4008 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4009 // should usually be true. This only needs to be set to false if the lack of
4010 // odr-use cannot be determined from the current context (for instance,
4011 // because the name denotes a virtual function and was written without an
4012 // explicit nested-name-specifier).
4013 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4014 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4015 bool MightBeOdrUse = true);
4016 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4017 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4018 void MarkMemberReferenced(MemberExpr *E);
4019
4020 void UpdateMarkingForLValueToRValue(Expr *E);
4021 void CleanupVarDeclMarking();
4022
4023 enum TryCaptureKind {
4024 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4025 };
4026
4027 /// \brief Try to capture the given variable.
4028 ///
4029 /// \param Var The variable to capture.
4030 ///
4031 /// \param Loc The location at which the capture occurs.
4032 ///
4033 /// \param Kind The kind of capture, which may be implicit (for either a
4034 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4035 ///
4036 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4037 /// an explicit lambda capture.
4038 ///
4039 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4040 /// captures or diagnose errors. If false, this routine merely check whether
4041 /// the capture can occur without performing the capture itself or complaining
4042 /// if the variable cannot be captured.
4043 ///
4044 /// \param CaptureType Will be set to the type of the field used to capture
4045 /// this variable in the innermost block or lambda. Only valid when the
4046 /// variable can be captured.
4047 ///
4048 /// \param DeclRefType Will be set to the type of a reference to the capture
4049 /// from within the current scope. Only valid when the variable can be
4050 /// captured.
4051 ///
4052 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4053 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4054 /// This is useful when enclosing lambdas must speculatively capture
4055 /// variables that may or may not be used in certain specializations of
4056 /// a nested generic lambda.
4057 ///
4058 /// \returns true if an error occurred (i.e., the variable cannot be
4059 /// captured) and false if the capture succeeded.
4060 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4061 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4062 QualType &CaptureType,
4063 QualType &DeclRefType,
4064 const unsigned *const FunctionScopeIndexToStopAt);
4065
4066 /// \brief Try to capture the given variable.
4067 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4068 TryCaptureKind Kind = TryCapture_Implicit,
4069 SourceLocation EllipsisLoc = SourceLocation());
4070
4071 /// \brief Checks if the variable must be captured.
4072 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4073
4074 /// \brief Given a variable, determine the type that a reference to that
4075 /// variable will have in the given scope.
4076 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4077
4078 /// Mark all of the declarations referenced within a particular AST node as
4079 /// referenced. Used when template instantiation instantiates a non-dependent
4080 /// type -- entities referenced by the type are now referenced.
4081 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4082 void MarkDeclarationsReferencedInExpr(Expr *E,
4083 bool SkipLocalVariables = false);
4084
4085 /// \brief Try to recover by turning the given expression into a
4086 /// call. Returns true if recovery was attempted or an error was
4087 /// emitted; this may also leave the ExprResult invalid.
4088 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4089 bool ForceComplain = false,
4090 bool (*IsPlausibleResult)(QualType) = nullptr);
4091
4092 /// \brief Figure out if an expression could be turned into a call.
4093 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4094 UnresolvedSetImpl &NonTemplateOverloads);
4095
4096 /// \brief Conditionally issue a diagnostic based on the current
4097 /// evaluation context.
4098 ///
4099 /// \param Statement If Statement is non-null, delay reporting the
4100 /// diagnostic until the function body is parsed, and then do a basic
4101 /// reachability analysis to determine if the statement is reachable.
4102 /// If it is unreachable, the diagnostic will not be emitted.
4103 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4104 const PartialDiagnostic &PD);
4105
4106 // Primary Expressions.
4107 SourceRange getExprRange(Expr *E) const;
4108
4109 ExprResult ActOnIdExpression(
4110 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4111 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4112 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4113 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4114
4115 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4116 TemplateArgumentListInfo &Buffer,
4117 DeclarationNameInfo &NameInfo,
4118 const TemplateArgumentListInfo *&TemplateArgs);
4119
4120 bool
4121 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4122 std::unique_ptr<CorrectionCandidateCallback> CCC,
4123 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4124 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4125
4126 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4127 IdentifierInfo *II,
4128 bool AllowBuiltinCreation=false);
4129
4130 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4131 SourceLocation TemplateKWLoc,
4132 const DeclarationNameInfo &NameInfo,
4133 bool isAddressOfOperand,
4134 const TemplateArgumentListInfo *TemplateArgs);
4135
4136 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4137 ExprValueKind VK,
4138 SourceLocation Loc,
4139 const CXXScopeSpec *SS = nullptr);
4140 ExprResult
4141 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4142 const DeclarationNameInfo &NameInfo,
4143 const CXXScopeSpec *SS = nullptr,
4144 NamedDecl *FoundD = nullptr,
4145 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4146 ExprResult
4147 BuildAnonymousStructUnionMemberReference(
4148 const CXXScopeSpec &SS,
4149 SourceLocation nameLoc,
4150 IndirectFieldDecl *indirectField,
4151 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4152 Expr *baseObjectExpr = nullptr,
4153 SourceLocation opLoc = SourceLocation());
4154
4155 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4156 SourceLocation TemplateKWLoc,
4157 LookupResult &R,
4158 const TemplateArgumentListInfo *TemplateArgs,
4159 const Scope *S);
4160 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4161 SourceLocation TemplateKWLoc,
4162 LookupResult &R,
4163 const TemplateArgumentListInfo *TemplateArgs,
4164 bool IsDefiniteInstance,
4165 const Scope *S);
4166 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4167 const LookupResult &R,
4168 bool HasTrailingLParen);
4169
4170 ExprResult
4171 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4172 const DeclarationNameInfo &NameInfo,
4173 bool IsAddressOfOperand, const Scope *S,
4174 TypeSourceInfo **RecoveryTSI = nullptr);
4175
4176 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4177 SourceLocation TemplateKWLoc,
4178 const DeclarationNameInfo &NameInfo,
4179 const TemplateArgumentListInfo *TemplateArgs);
4180
4181 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4182 LookupResult &R,
4183 bool NeedsADL,
4184 bool AcceptInvalidDecl = false);
4185 ExprResult BuildDeclarationNameExpr(
4186 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4187 NamedDecl *FoundD = nullptr,
4188 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4189 bool AcceptInvalidDecl = false);
4190
4191 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4192 DeclarationNameInfo &SuffixInfo,
4193 ArrayRef<Expr *> Args,
4194 SourceLocation LitEndLoc,
4195 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4196
4197 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4198 PredefinedExpr::IdentType IT);
4199 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4200 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4201
4202 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4203
4204 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4205 ExprResult ActOnCharacterConstant(const Token &Tok,
4206 Scope *UDLScope = nullptr);
4207 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4208 ExprResult ActOnParenListExpr(SourceLocation L,
4209 SourceLocation R,
4210 MultiExprArg Val);
4211
4212 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4213 /// fragments (e.g. "foo" "bar" L"baz").
4214 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4215 Scope *UDLScope = nullptr);
4216
4217 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4218 SourceLocation DefaultLoc,
4219 SourceLocation RParenLoc,
4220 Expr *ControllingExpr,
4221 ArrayRef<ParsedType> ArgTypes,
4222 ArrayRef<Expr *> ArgExprs);
4223 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4224 SourceLocation DefaultLoc,
4225 SourceLocation RParenLoc,
4226 Expr *ControllingExpr,
4227 ArrayRef<TypeSourceInfo *> Types,
4228 ArrayRef<Expr *> Exprs);
4229
4230 // Binary/Unary Operators. 'Tok' is the token for the operator.
4231 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4232 Expr *InputExpr);
4233 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4234 UnaryOperatorKind Opc, Expr *Input);
4235 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4236 tok::TokenKind Op, Expr *Input);
4237
4238 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4239
4240 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4241 SourceLocation OpLoc,
4242 UnaryExprOrTypeTrait ExprKind,
4243 SourceRange R);
4244 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4245 UnaryExprOrTypeTrait ExprKind);
4246 ExprResult
4247 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4248 UnaryExprOrTypeTrait ExprKind,
4249 bool IsType, void *TyOrEx,
4250 SourceRange ArgRange);
4251
4252 ExprResult CheckPlaceholderExpr(Expr *E);
4253 bool CheckVecStepExpr(Expr *E);
4254
4255 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4256 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4257 SourceRange ExprRange,
4258 UnaryExprOrTypeTrait ExprKind);
4259 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4260 SourceLocation OpLoc,
4261 IdentifierInfo &Name,
4262 SourceLocation NameLoc,
4263 SourceLocation RParenLoc);
4264 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4265 tok::TokenKind Kind, Expr *Input);
4266
4267 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4268 Expr *Idx, SourceLocation RLoc);
4269 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4270 Expr *Idx, SourceLocation RLoc);
4271 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4272 Expr *LowerBound, SourceLocation ColonLoc,
4273 Expr *Length, SourceLocation RBLoc);
4274
4275 // This struct is for use by ActOnMemberAccess to allow
4276 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4277 // changing the access operator from a '.' to a '->' (to see if that is the
4278 // change needed to fix an error about an unknown member, e.g. when the class
4279 // defines a custom operator->).
4280 struct ActOnMemberAccessExtraArgs {
4281 Scope *S;
4282 UnqualifiedId &Id;
4283 Decl *ObjCImpDecl;
4284 };
4285
4286 ExprResult BuildMemberReferenceExpr(
4287 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4288 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4289 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4290 const TemplateArgumentListInfo *TemplateArgs,
4291 const Scope *S,
4292 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4293
4294 ExprResult
4295 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4296 bool IsArrow, const CXXScopeSpec &SS,
4297 SourceLocation TemplateKWLoc,
4298 NamedDecl *FirstQualifierInScope, LookupResult &R,
4299 const TemplateArgumentListInfo *TemplateArgs,
4300 const Scope *S,
4301 bool SuppressQualifierCheck = false,
4302 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4303
4304 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4305 SourceLocation OpLoc,
4306 const CXXScopeSpec &SS, FieldDecl *Field,
4307 DeclAccessPair FoundDecl,
4308 const DeclarationNameInfo &MemberNameInfo);
4309
4310 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4311
4312 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4313 const CXXScopeSpec &SS,
4314 const LookupResult &R);
4315
4316 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4317 bool IsArrow, SourceLocation OpLoc,
4318 const CXXScopeSpec &SS,
4319 SourceLocation TemplateKWLoc,
4320 NamedDecl *FirstQualifierInScope,
4321 const DeclarationNameInfo &NameInfo,
4322 const TemplateArgumentListInfo *TemplateArgs);
4323
4324 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4325 SourceLocation OpLoc,
4326 tok::TokenKind OpKind,
4327 CXXScopeSpec &SS,
4328 SourceLocation TemplateKWLoc,
4329 UnqualifiedId &Member,
4330 Decl *ObjCImpDecl);
4331
4332 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4333 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4334 FunctionDecl *FDecl,
4335 const FunctionProtoType *Proto,
4336 ArrayRef<Expr *> Args,
4337 SourceLocation RParenLoc,
4338 bool ExecConfig = false);
4339 void CheckStaticArrayArgument(SourceLocation CallLoc,
4340 ParmVarDecl *Param,
4341 const Expr *ArgExpr);
4342
4343 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4344 /// This provides the location of the left/right parens and a list of comma
4345 /// locations.
4346 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4347 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4348 Expr *ExecConfig = nullptr,
4349 bool IsExecConfig = false);
4350 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4351 SourceLocation LParenLoc,
4352 ArrayRef<Expr *> Arg,
4353 SourceLocation RParenLoc,
4354 Expr *Config = nullptr,
4355 bool IsExecConfig = false);
4356
4357 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4358 MultiExprArg ExecConfig,
4359 SourceLocation GGGLoc);
4360
4361 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4362 Declarator &D, ParsedType &Ty,
4363 SourceLocation RParenLoc, Expr *CastExpr);
4364 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4365 TypeSourceInfo *Ty,
4366 SourceLocation RParenLoc,
4367 Expr *Op);
4368 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4369
4370 /// \brief Build an altivec or OpenCL literal.
4371 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4372 SourceLocation RParenLoc, Expr *E,
4373 TypeSourceInfo *TInfo);
4374
4375 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4376
4377 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4378 ParsedType Ty,
4379 SourceLocation RParenLoc,
4380 Expr *InitExpr);
4381
4382 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4383 TypeSourceInfo *TInfo,
4384 SourceLocation RParenLoc,
4385 Expr *LiteralExpr);
4386
4387 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4388 MultiExprArg InitArgList,
4389 SourceLocation RBraceLoc);
4390
4391 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4392 SourceLocation Loc,
4393 bool GNUSyntax,
4394 ExprResult Init);
4395
4396private:
4397 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4398
4399public:
4400 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4401 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4402 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4403 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4404 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4405 Expr *LHSExpr, Expr *RHSExpr);
4406
4407 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4408
4409 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4410 /// in the case of a the GNU conditional expr extension.
4411 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4412 SourceLocation ColonLoc,
4413 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4414
4415 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4416 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4417 LabelDecl *TheDecl);
4418
4419 void ActOnStartStmtExpr();
4420 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4421 SourceLocation RPLoc); // "({..})"
4422 void ActOnStmtExprError();
4423
4424 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4425 struct OffsetOfComponent {
4426 SourceLocation LocStart, LocEnd;
4427 bool isBrackets; // true if [expr], false if .ident
4428 union {
4429 IdentifierInfo *IdentInfo;
4430 Expr *E;
4431 } U;
4432 };
4433
4434 /// __builtin_offsetof(type, a.b[123][456].c)
4435 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4436 TypeSourceInfo *TInfo,
4437 ArrayRef<OffsetOfComponent> Components,
4438 SourceLocation RParenLoc);
4439 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4440 SourceLocation BuiltinLoc,
4441 SourceLocation TypeLoc,
4442 ParsedType ParsedArgTy,
4443 ArrayRef<OffsetOfComponent> Components,
4444 SourceLocation RParenLoc);
4445
4446 // __builtin_choose_expr(constExpr, expr1, expr2)
4447 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4448 Expr *CondExpr, Expr *LHSExpr,
4449 Expr *RHSExpr, SourceLocation RPLoc);
4450
4451 // __builtin_va_arg(expr, type)
4452 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4453 SourceLocation RPLoc);
4454 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4455 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4456
4457 // __null
4458 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4459
4460 bool CheckCaseExpression(Expr *E);
4461
4462 /// \brief Describes the result of an "if-exists" condition check.
4463 enum IfExistsResult {
4464 /// \brief The symbol exists.
4465 IER_Exists,
4466
4467 /// \brief The symbol does not exist.
4468 IER_DoesNotExist,
4469
4470 /// \brief The name is a dependent name, so the results will differ
4471 /// from one instantiation to the next.
4472 IER_Dependent,
4473
4474 /// \brief An error occurred.
4475 IER_Error
4476 };
4477
4478 IfExistsResult
4479 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4480 const DeclarationNameInfo &TargetNameInfo);
4481
4482 IfExistsResult
4483 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4484 bool IsIfExists, CXXScopeSpec &SS,
4485 UnqualifiedId &Name);
4486
4487 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4488 bool IsIfExists,
4489 NestedNameSpecifierLoc QualifierLoc,
4490 DeclarationNameInfo NameInfo,
4491 Stmt *Nested);
4492 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4493 bool IsIfExists,
4494 CXXScopeSpec &SS, UnqualifiedId &Name,
4495 Stmt *Nested);
4496
4497 //===------------------------- "Block" Extension ------------------------===//
4498
4499 /// ActOnBlockStart - This callback is invoked when a block literal is
4500 /// started.
4501 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4502
4503 /// ActOnBlockArguments - This callback allows processing of block arguments.
4504 /// If there are no arguments, this is still invoked.
4505 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4506 Scope *CurScope);
4507
4508 /// ActOnBlockError - If there is an error parsing a block, this callback
4509 /// is invoked to pop the information about the block from the action impl.
4510 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4511
4512 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4513 /// literal was successfully completed. ^(int x){...}
4514 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4515 Scope *CurScope);
4516
4517 //===---------------------------- Clang Extensions ----------------------===//
4518
4519 /// __builtin_convertvector(...)
4520 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4521 SourceLocation BuiltinLoc,
4522 SourceLocation RParenLoc);
4523
4524 //===---------------------------- OpenCL Features -----------------------===//
4525
4526 /// __builtin_astype(...)
4527 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4528 SourceLocation BuiltinLoc,
4529 SourceLocation RParenLoc);
4530
4531 //===---------------------------- C++ Features --------------------------===//
4532
4533 // Act on C++ namespaces
4534 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4535 SourceLocation NamespaceLoc,
4536 SourceLocation IdentLoc,
4537 IdentifierInfo *Ident,
4538 SourceLocation LBrace,
4539 AttributeList *AttrList,
4540 UsingDirectiveDecl * &UsingDecl);
4541 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4542
4543 NamespaceDecl *getStdNamespace() const;
4544 NamespaceDecl *getOrCreateStdNamespace();
4545
4546 NamespaceDecl *lookupStdExperimentalNamespace();
4547
4548 CXXRecordDecl *getStdBadAlloc() const;
4549 EnumDecl *getStdAlignValT() const;
4550
4551 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4552 /// it is and Element is not NULL, assigns the element type to Element.
4553 bool isStdInitializerList(QualType Ty, QualType *Element);
4554
4555 /// \brief Looks for the std::initializer_list template and instantiates it
4556 /// with Element, or emits an error if it's not found.
4557 ///
4558 /// \returns The instantiated template, or null on error.
4559 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4560
4561 /// \brief Determine whether Ctor is an initializer-list constructor, as
4562 /// defined in [dcl.init.list]p2.
4563 bool isInitListConstructor(const FunctionDecl *Ctor);
4564
4565 Decl *ActOnUsingDirective(Scope *CurScope,
4566 SourceLocation UsingLoc,
4567 SourceLocation NamespcLoc,
4568 CXXScopeSpec &SS,
4569 SourceLocation IdentLoc,
4570 IdentifierInfo *NamespcName,
4571 AttributeList *AttrList);
4572
4573 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4574
4575 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4576 SourceLocation NamespaceLoc,
4577 SourceLocation AliasLoc,
4578 IdentifierInfo *Alias,
4579 CXXScopeSpec &SS,
4580 SourceLocation IdentLoc,
4581 IdentifierInfo *Ident);
4582
4583 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4584 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4585 const LookupResult &PreviousDecls,
4586 UsingShadowDecl *&PrevShadow);
4587 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4588 NamedDecl *Target,
4589 UsingShadowDecl *PrevDecl);
4590
4591 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4592 bool HasTypenameKeyword,
4593 const CXXScopeSpec &SS,
4594 SourceLocation NameLoc,
4595 const LookupResult &Previous);
4596 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4597 bool HasTypename,
4598 const CXXScopeSpec &SS,
4599 const DeclarationNameInfo &NameInfo,
4600 SourceLocation NameLoc);
4601
4602 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4603 SourceLocation UsingLoc,
4604 bool HasTypenameKeyword,
4605 SourceLocation TypenameLoc,
4606 CXXScopeSpec &SS,
4607 DeclarationNameInfo NameInfo,
4608 SourceLocation EllipsisLoc,
4609 AttributeList *AttrList,
4610 bool IsInstantiation);
4611 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4612 ArrayRef<NamedDecl *> Expansions);
4613
4614 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4615
4616 /// Given a derived-class using shadow declaration for a constructor and the
4617 /// correspnding base class constructor, find or create the implicit
4618 /// synthesized derived class constructor to use for this initialization.
4619 CXXConstructorDecl *
4620 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4621 ConstructorUsingShadowDecl *DerivedShadow);
4622
4623 Decl *ActOnUsingDeclaration(Scope *CurScope,
4624 AccessSpecifier AS,
4625 SourceLocation UsingLoc,
4626 SourceLocation TypenameLoc,
4627 CXXScopeSpec &SS,
4628 UnqualifiedId &Name,
4629 SourceLocation EllipsisLoc,
4630 AttributeList *AttrList);
4631 Decl *ActOnAliasDeclaration(Scope *CurScope,
4632 AccessSpecifier AS,
4633 MultiTemplateParamsArg TemplateParams,
4634 SourceLocation UsingLoc,
4635 UnqualifiedId &Name,
4636 AttributeList *AttrList,
4637 TypeResult Type,
4638 Decl *DeclFromDeclSpec);
4639
4640 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4641 /// including handling of its default argument expressions.
4642 ///
4643 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4644 ExprResult
4645 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4646 NamedDecl *FoundDecl,
4647 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4648 bool HadMultipleCandidates, bool IsListInitialization,
4649 bool IsStdInitListInitialization,
4650 bool RequiresZeroInit, unsigned ConstructKind,
4651 SourceRange ParenRange);
4652
4653 /// Build a CXXConstructExpr whose constructor has already been resolved if
4654 /// it denotes an inherited constructor.
4655 ExprResult
4656 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4657 CXXConstructorDecl *Constructor, bool Elidable,
4658 MultiExprArg Exprs,
4659 bool HadMultipleCandidates, bool IsListInitialization,
4660 bool IsStdInitListInitialization,
4661 bool RequiresZeroInit, unsigned ConstructKind,
4662 SourceRange ParenRange);
4663
4664 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4665 // the constructor can be elidable?
4666 ExprResult
4667 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4668 NamedDecl *FoundDecl,
4669 CXXConstructorDecl *Constructor, bool Elidable,
4670 MultiExprArg Exprs, bool HadMultipleCandidates,
4671 bool IsListInitialization,
4672 bool IsStdInitListInitialization, bool RequiresZeroInit,
4673 unsigned ConstructKind, SourceRange ParenRange);
4674
4675 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4676
4677
4678 /// Instantiate or parse a C++ default argument expression as necessary.
4679 /// Return true on error.
4680 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4681 ParmVarDecl *Param);
4682
4683 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4684 /// the default expr if needed.
4685 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4686 FunctionDecl *FD,
4687 ParmVarDecl *Param);
4688
4689 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4690 /// constructed variable.
4691 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4692
4693 /// \brief Helper class that collects exception specifications for
4694 /// implicitly-declared special member functions.
4695 class ImplicitExceptionSpecification {
4696 // Pointer to allow copying
4697 Sema *Self;
4698 // We order exception specifications thus:
4699 // noexcept is the most restrictive, but is only used in C++11.
4700 // throw() comes next.
4701 // Then a throw(collected exceptions)
4702 // Finally no specification, which is expressed as noexcept(false).
4703 // throw(...) is used instead if any called function uses it.
4704 ExceptionSpecificationType ComputedEST;
4705 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4706 SmallVector<QualType, 4> Exceptions;
4707
4708 void ClearExceptions() {
4709 ExceptionsSeen.clear();
4710 Exceptions.clear();
4711 }
4712
4713 public:
4714 explicit ImplicitExceptionSpecification(Sema &Self)
4715 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4716 if (!Self.getLangOpts().CPlusPlus11)
4717 ComputedEST = EST_DynamicNone;
4718 }
4719
4720 /// \brief Get the computed exception specification type.
4721 ExceptionSpecificationType getExceptionSpecType() const {
4722 assert(ComputedEST != EST_ComputedNoexcept &&(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 4723, __extension__ __PRETTY_FUNCTION__))
4723 "noexcept(expr) should not be a possible result")(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 4723, __extension__ __PRETTY_FUNCTION__))
;
4724 return ComputedEST;
4725 }
4726
4727 /// \brief The number of exceptions in the exception specification.
4728 unsigned size() const { return Exceptions.size(); }
4729
4730 /// \brief The set of exceptions in the exception specification.
4731 const QualType *data() const { return Exceptions.data(); }
4732
4733 /// \brief Integrate another called method into the collected data.
4734 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4735
4736 /// \brief Integrate an invoked expression into the collected data.
4737 void CalledExpr(Expr *E);
4738
4739 /// \brief Overwrite an EPI's exception specification with this
4740 /// computed exception specification.
4741 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4742 FunctionProtoType::ExceptionSpecInfo ESI;
4743 ESI.Type = getExceptionSpecType();
4744 if (ESI.Type == EST_Dynamic) {
4745 ESI.Exceptions = Exceptions;
4746 } else if (ESI.Type == EST_None) {
4747 /// C++11 [except.spec]p14:
4748 /// The exception-specification is noexcept(false) if the set of
4749 /// potential exceptions of the special member function contains "any"
4750 ESI.Type = EST_ComputedNoexcept;
4751 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4752 tok::kw_false).get();
4753 }
4754 return ESI;
4755 }
4756 };
4757
4758 /// \brief Determine what sort of exception specification a defaulted
4759 /// copy constructor of a class will have.
4760 ImplicitExceptionSpecification
4761 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4762 CXXMethodDecl *MD);
4763
4764 /// \brief Determine what sort of exception specification a defaulted
4765 /// default constructor of a class will have, and whether the parameter
4766 /// will be const.
4767 ImplicitExceptionSpecification
4768 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4769
4770 /// \brief Determine what sort of exception specification a defautled
4771 /// copy assignment operator of a class will have, and whether the
4772 /// parameter will be const.
4773 ImplicitExceptionSpecification
4774 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4775
4776 /// \brief Determine what sort of exception specification a defaulted move
4777 /// constructor of a class will have.
4778 ImplicitExceptionSpecification
4779 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4780
4781 /// \brief Determine what sort of exception specification a defaulted move
4782 /// assignment operator of a class will have.
4783 ImplicitExceptionSpecification
4784 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4785
4786 /// \brief Determine what sort of exception specification a defaulted
4787 /// destructor of a class will have.
4788 ImplicitExceptionSpecification
4789 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4790
4791 /// \brief Determine what sort of exception specification an inheriting
4792 /// constructor of a class will have.
4793 ImplicitExceptionSpecification
4794 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4795 CXXConstructorDecl *CD);
4796
4797 /// \brief Evaluate the implicit exception specification for a defaulted
4798 /// special member function.
4799 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4800
4801 /// \brief Check the given exception-specification and update the
4802 /// exception specification information with the results.
4803 void checkExceptionSpecification(bool IsTopLevel,
4804 ExceptionSpecificationType EST,
4805 ArrayRef<ParsedType> DynamicExceptions,
4806 ArrayRef<SourceRange> DynamicExceptionRanges,
4807 Expr *NoexceptExpr,
4808 SmallVectorImpl<QualType> &Exceptions,
4809 FunctionProtoType::ExceptionSpecInfo &ESI);
4810
4811 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4812 /// parse an exception specification to work around a libstdc++ bug.
4813 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4814
4815 /// \brief Add an exception-specification to the given member function
4816 /// (or member function template). The exception-specification was parsed
4817 /// after the method itself was declared.
4818 void actOnDelayedExceptionSpecification(Decl *Method,
4819 ExceptionSpecificationType EST,
4820 SourceRange SpecificationRange,
4821 ArrayRef<ParsedType> DynamicExceptions,
4822 ArrayRef<SourceRange> DynamicExceptionRanges,
4823 Expr *NoexceptExpr);
4824
4825 class InheritedConstructorInfo;
4826
4827 /// \brief Determine if a special member function should have a deleted
4828 /// definition when it is defaulted.
4829 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4830 InheritedConstructorInfo *ICI = nullptr,
4831 bool Diagnose = false);
4832
4833 /// \brief Declare the implicit default constructor for the given class.
4834 ///
4835 /// \param ClassDecl The class declaration into which the implicit
4836 /// default constructor will be added.
4837 ///
4838 /// \returns The implicitly-declared default constructor.
4839 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4840 CXXRecordDecl *ClassDecl);
4841
4842 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4843 /// defining this constructor as the default constructor.
4844 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4845 CXXConstructorDecl *Constructor);
4846
4847 /// \brief Declare the implicit destructor for the given class.
4848 ///
4849 /// \param ClassDecl The class declaration into which the implicit
4850 /// destructor will be added.
4851 ///
4852 /// \returns The implicitly-declared destructor.
4853 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4854
4855 /// DefineImplicitDestructor - Checks for feasibility of
4856 /// defining this destructor as the default destructor.
4857 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4858 CXXDestructorDecl *Destructor);
4859
4860 /// \brief Build an exception spec for destructors that don't have one.
4861 ///
4862 /// C++11 says that user-defined destructors with no exception spec get one
4863 /// that looks as if the destructor was implicitly declared.
4864 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4865 CXXDestructorDecl *Destructor);
4866
4867 /// \brief Define the specified inheriting constructor.
4868 void DefineInheritingConstructor(SourceLocation UseLoc,
4869 CXXConstructorDecl *Constructor);
4870
4871 /// \brief Declare the implicit copy constructor for the given class.
4872 ///
4873 /// \param ClassDecl The class declaration into which the implicit
4874 /// copy constructor will be added.
4875 ///
4876 /// \returns The implicitly-declared copy constructor.
4877 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4878
4879 /// DefineImplicitCopyConstructor - Checks for feasibility of
4880 /// defining this constructor as the copy constructor.
4881 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4882 CXXConstructorDecl *Constructor);
4883
4884 /// \brief Declare the implicit move constructor for the given class.
4885 ///
4886 /// \param ClassDecl The Class declaration into which the implicit
4887 /// move constructor will be added.
4888 ///
4889 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4890 /// declared.
4891 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4892
4893 /// DefineImplicitMoveConstructor - Checks for feasibility of
4894 /// defining this constructor as the move constructor.
4895 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4896 CXXConstructorDecl *Constructor);
4897
4898 /// \brief Declare the implicit copy assignment operator for the given class.
4899 ///
4900 /// \param ClassDecl The class declaration into which the implicit
4901 /// copy assignment operator will be added.
4902 ///
4903 /// \returns The implicitly-declared copy assignment operator.
4904 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4905
4906 /// \brief Defines an implicitly-declared copy assignment operator.
4907 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4908 CXXMethodDecl *MethodDecl);
4909
4910 /// \brief Declare the implicit move assignment operator for the given class.
4911 ///
4912 /// \param ClassDecl The Class declaration into which the implicit
4913 /// move assignment operator will be added.
4914 ///
4915 /// \returns The implicitly-declared move assignment operator, or NULL if it
4916 /// wasn't declared.
4917 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4918
4919 /// \brief Defines an implicitly-declared move assignment operator.
4920 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4921 CXXMethodDecl *MethodDecl);
4922
4923 /// \brief Force the declaration of any implicitly-declared members of this
4924 /// class.
4925 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4926
4927 /// \brief Check a completed declaration of an implicit special member.
4928 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4929
4930 /// \brief Determine whether the given function is an implicitly-deleted
4931 /// special member function.
4932 bool isImplicitlyDeleted(FunctionDecl *FD);
4933
4934 /// \brief Check whether 'this' shows up in the type of a static member
4935 /// function after the (naturally empty) cv-qualifier-seq would be.
4936 ///
4937 /// \returns true if an error occurred.
4938 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4939
4940 /// \brief Whether this' shows up in the exception specification of a static
4941 /// member function.
4942 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4943
4944 /// \brief Check whether 'this' shows up in the attributes of the given
4945 /// static member function.
4946 ///
4947 /// \returns true if an error occurred.
4948 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4949
4950 /// MaybeBindToTemporary - If the passed in expression has a record type with
4951 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4952 /// it simply returns the passed in expression.
4953 ExprResult MaybeBindToTemporary(Expr *E);
4954
4955 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4956 MultiExprArg ArgsPtr,
4957 SourceLocation Loc,
4958 SmallVectorImpl<Expr*> &ConvertedArgs,
4959 bool AllowExplicit = false,
4960 bool IsListInitialization = false);
4961
4962 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4963 SourceLocation NameLoc,
4964 IdentifierInfo &Name);
4965
4966 ParsedType getDestructorName(SourceLocation TildeLoc,
4967 IdentifierInfo &II, SourceLocation NameLoc,
4968 Scope *S, CXXScopeSpec &SS,
4969 ParsedType ObjectType,
4970 bool EnteringContext);
4971
4972 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4973 ParsedType ObjectType);
4974
4975 // Checks that reinterpret casts don't have undefined behavior.
4976 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4977 bool IsDereference, SourceRange Range);
4978
4979 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4980 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4981 tok::TokenKind Kind,
4982 SourceLocation LAngleBracketLoc,
4983 Declarator &D,
4984 SourceLocation RAngleBracketLoc,
4985 SourceLocation LParenLoc,
4986 Expr *E,
4987 SourceLocation RParenLoc);
4988
4989 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4990 tok::TokenKind Kind,
4991 TypeSourceInfo *Ty,
4992 Expr *E,
4993 SourceRange AngleBrackets,
4994 SourceRange Parens);
4995
4996 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4997 SourceLocation TypeidLoc,
4998 TypeSourceInfo *Operand,
4999 SourceLocation RParenLoc);
5000 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5001 SourceLocation TypeidLoc,
5002 Expr *Operand,
5003 SourceLocation RParenLoc);
5004
5005 /// ActOnCXXTypeid - Parse typeid( something ).
5006 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5007 SourceLocation LParenLoc, bool isType,
5008 void *TyOrExpr,
5009 SourceLocation RParenLoc);
5010
5011 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5012 SourceLocation TypeidLoc,
5013 TypeSourceInfo *Operand,
5014 SourceLocation RParenLoc);
5015 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5016 SourceLocation TypeidLoc,
5017 Expr *Operand,
5018 SourceLocation RParenLoc);
5019
5020 /// ActOnCXXUuidof - Parse __uuidof( something ).
5021 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5022 SourceLocation LParenLoc, bool isType,
5023 void *TyOrExpr,
5024 SourceLocation RParenLoc);
5025
5026 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
5027 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5028 tok::TokenKind Operator,
5029 SourceLocation EllipsisLoc, Expr *RHS,
5030 SourceLocation RParenLoc);
5031 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5032 BinaryOperatorKind Operator,
5033 SourceLocation EllipsisLoc, Expr *RHS,
5034 SourceLocation RParenLoc);
5035 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5036 BinaryOperatorKind Operator);
5037
5038 //// ActOnCXXThis - Parse 'this' pointer.
5039 ExprResult ActOnCXXThis(SourceLocation loc);
5040
5041 /// \brief Try to retrieve the type of the 'this' pointer.
5042 ///
5043 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5044 QualType getCurrentThisType();
5045
5046 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
5047 /// current context not being a non-static member function. In such cases,
5048 /// this provides the type used for 'this'.
5049 QualType CXXThisTypeOverride;
5050
5051 /// \brief RAII object used to temporarily allow the C++ 'this' expression
5052 /// to be used, with the given qualifiers on the current class type.
5053 class CXXThisScopeRAII {
5054 Sema &S;
5055 QualType OldCXXThisTypeOverride;
5056 bool Enabled;
5057
5058 public:
5059 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
5060 /// using the given declaration (which is either a class template or a
5061 /// class) along with the given qualifiers.
5062 /// along with the qualifiers placed on '*this'.
5063 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
5064 bool Enabled = true);
5065
5066 ~CXXThisScopeRAII();
5067 };
5068
5069 /// \brief Make sure the value of 'this' is actually available in the current
5070 /// context, if it is a potentially evaluated context.
5071 ///
5072 /// \param Loc The location at which the capture of 'this' occurs.
5073 ///
5074 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5075 /// capture list.
5076 ///
5077 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5078 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5079 /// This is useful when enclosing lambdas must speculatively capture
5080 /// 'this' that may or may not be used in certain specializations of
5081 /// a nested generic lambda (depending on whether the name resolves to
5082 /// a non-static member function or a static function).
5083 /// \return returns 'true' if failed, 'false' if success.
5084 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5085 bool BuildAndDiagnose = true,
5086 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5087 bool ByCopy = false);
5088
5089 /// \brief Determine whether the given type is the type of *this that is used
5090 /// outside of the body of a member function for a type that is currently
5091 /// being defined.
5092 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5093
5094 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5095 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5096
5097
5098 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5099 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5100
5101 ExprResult
5102 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5103 SourceLocation AtLoc, SourceLocation RParen);
5104
5105 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5106 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5107
5108 //// ActOnCXXThrow - Parse throw expressions.
5109 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5110 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5111 bool IsThrownVarInScope);
5112 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5113
5114 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5115 /// Can be interpreted either as function-style casting ("int(x)")
5116 /// or class type construction ("ClassType(x,y,z)")
5117 /// or creation of a value-initialized type ("int()").
5118 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5119 SourceLocation LParenOrBraceLoc,
5120 MultiExprArg Exprs,
5121 SourceLocation RParenOrBraceLoc,
5122 bool ListInitialization);
5123
5124 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5125 SourceLocation LParenLoc,
5126 MultiExprArg Exprs,
5127 SourceLocation RParenLoc,
5128 bool ListInitialization);
5129
5130 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5131 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5132 SourceLocation PlacementLParen,
5133 MultiExprArg PlacementArgs,
5134 SourceLocation PlacementRParen,
5135 SourceRange TypeIdParens, Declarator &D,
5136 Expr *Initializer);
5137 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5138 SourceLocation PlacementLParen,
5139 MultiExprArg PlacementArgs,
5140 SourceLocation PlacementRParen,
5141 SourceRange TypeIdParens,
5142 QualType AllocType,
5143 TypeSourceInfo *AllocTypeInfo,
5144 Expr *ArraySize,
5145 SourceRange DirectInitRange,
5146 Expr *Initializer);
5147
5148 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5149 SourceRange R);
5150 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5151 bool UseGlobal, QualType AllocType, bool IsArray,
5152 bool &PassAlignment, MultiExprArg PlaceArgs,
5153 FunctionDecl *&OperatorNew,
5154 FunctionDecl *&OperatorDelete,
5155 bool Diagnose = true);
5156 void DeclareGlobalNewDelete();
5157 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5158 ArrayRef<QualType> Params);
5159
5160 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5161 DeclarationName Name, FunctionDecl* &Operator,
5162 bool Diagnose = true);
5163 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5164 bool CanProvideSize,
5165 bool Overaligned,
5166 DeclarationName Name);
5167 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5168 CXXRecordDecl *RD);
5169
5170 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5171 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5172 bool UseGlobal, bool ArrayForm,
5173 Expr *Operand);
5174 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5175 bool IsDelete, bool CallCanBeVirtual,
5176 bool WarnOnNonAbstractTypes,
5177 SourceLocation DtorLoc);
5178
5179 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5180 Expr *Operand, SourceLocation RParen);
5181 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5182 SourceLocation RParen);
5183
5184 /// \brief Parsed one of the type trait support pseudo-functions.
5185 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5186 ArrayRef<ParsedType> Args,
5187 SourceLocation RParenLoc);
5188 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5189 ArrayRef<TypeSourceInfo *> Args,
5190 SourceLocation RParenLoc);
5191
5192 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5193 /// pseudo-functions.
5194 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5195 SourceLocation KWLoc,
5196 ParsedType LhsTy,
5197 Expr *DimExpr,
5198 SourceLocation RParen);
5199
5200 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5201 SourceLocation KWLoc,
5202 TypeSourceInfo *TSInfo,
5203 Expr *DimExpr,
5204 SourceLocation RParen);
5205
5206 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5207 /// pseudo-functions.
5208 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5209 SourceLocation KWLoc,
5210 Expr *Queried,
5211 SourceLocation RParen);
5212
5213 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5214 SourceLocation KWLoc,
5215 Expr *Queried,
5216 SourceLocation RParen);
5217
5218 ExprResult ActOnStartCXXMemberReference(Scope *S,
5219 Expr *Base,
5220 SourceLocation OpLoc,
5221 tok::TokenKind OpKind,
5222 ParsedType &ObjectType,
5223 bool &MayBePseudoDestructor);
5224
5225 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5226 SourceLocation OpLoc,
5227 tok::TokenKind OpKind,
5228 const CXXScopeSpec &SS,
5229 TypeSourceInfo *ScopeType,
5230 SourceLocation CCLoc,
5231 SourceLocation TildeLoc,
5232 PseudoDestructorTypeStorage DestroyedType);
5233
5234 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5235 SourceLocation OpLoc,
5236 tok::TokenKind OpKind,
5237 CXXScopeSpec &SS,
5238 UnqualifiedId &FirstTypeName,
5239 SourceLocation CCLoc,
5240 SourceLocation TildeLoc,
5241 UnqualifiedId &SecondTypeName);
5242
5243 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5244 SourceLocation OpLoc,
5245 tok::TokenKind OpKind,
5246 SourceLocation TildeLoc,
5247 const DeclSpec& DS);
5248
5249 /// MaybeCreateExprWithCleanups - If the current full-expression
5250 /// requires any cleanups, surround it with a ExprWithCleanups node.
5251 /// Otherwise, just returns the passed-in expression.
5252 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5253 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5254 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5255
5256 MaterializeTemporaryExpr *
5257 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5258 bool BoundToLvalueReference);
5259
5260 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5261 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5262 : SourceLocation());
5263 }
5264 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5265 bool DiscardedValue = false,
5266 bool IsConstexpr = false,
5267 bool IsLambdaInitCaptureInitializer = false);
5268 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5269
5270 // Marks SS invalid if it represents an incomplete type.
5271 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5272
5273 DeclContext *computeDeclContext(QualType T);
5274 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5275 bool EnteringContext = false);
5276 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5277 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5278
5279 /// \brief The parser has parsed a global nested-name-specifier '::'.
5280 ///
5281 /// \param CCLoc The location of the '::'.
5282 ///
5283 /// \param SS The nested-name-specifier, which will be updated in-place
5284 /// to reflect the parsed nested-name-specifier.
5285 ///
5286 /// \returns true if an error occurred, false otherwise.
5287 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5288
5289 /// \brief The parser has parsed a '__super' nested-name-specifier.
5290 ///
5291 /// \param SuperLoc The location of the '__super' keyword.
5292 ///
5293 /// \param ColonColonLoc The location of the '::'.
5294 ///
5295 /// \param SS The nested-name-specifier, which will be updated in-place
5296 /// to reflect the parsed nested-name-specifier.
5297 ///
5298 /// \returns true if an error occurred, false otherwise.
5299 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5300 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5301
5302 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5303 bool *CanCorrect = nullptr);
5304 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5305
5306 /// \brief Keeps information about an identifier in a nested-name-spec.
5307 ///
5308 struct NestedNameSpecInfo {
5309 /// \brief The type of the object, if we're parsing nested-name-specifier in
5310 /// a member access expression.
5311 ParsedType ObjectType;
5312
5313 /// \brief The identifier preceding the '::'.
5314 IdentifierInfo *Identifier;
5315
5316 /// \brief The location of the identifier.
5317 SourceLocation IdentifierLoc;
5318
5319 /// \brief The location of the '::'.
5320 SourceLocation CCLoc;
5321
5322 /// \brief Creates info object for the most typical case.
5323 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5324 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5325 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5326 CCLoc(ColonColonLoc) {
5327 }
5328
5329 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5330 SourceLocation ColonColonLoc, QualType ObjectType)
5331 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5332 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5333 }
5334 };
5335
5336 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5337 NestedNameSpecInfo &IdInfo);
5338
5339 bool BuildCXXNestedNameSpecifier(Scope *S,
5340 NestedNameSpecInfo &IdInfo,
5341 bool EnteringContext,
5342 CXXScopeSpec &SS,
5343 NamedDecl *ScopeLookupResult,
5344 bool ErrorRecoveryLookup,
5345 bool *IsCorrectedToColon = nullptr,
5346 bool OnlyNamespace = false);
5347
5348 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5349 ///
5350 /// \param S The scope in which this nested-name-specifier occurs.
5351 ///
5352 /// \param IdInfo Parser information about an identifier in the
5353 /// nested-name-spec.
5354 ///
5355 /// \param EnteringContext Whether we're entering the context nominated by
5356 /// this nested-name-specifier.
5357 ///
5358 /// \param SS The nested-name-specifier, which is both an input
5359 /// parameter (the nested-name-specifier before this type) and an
5360 /// output parameter (containing the full nested-name-specifier,
5361 /// including this new type).
5362 ///
5363 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5364 /// error recovery. In this case do not emit error message.
5365 ///
5366 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5367 /// are allowed. The bool value pointed by this parameter is set to 'true'
5368 /// if the identifier is treated as if it was followed by ':', not '::'.
5369 ///
5370 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5371 ///
5372 /// \returns true if an error occurred, false otherwise.
5373 bool ActOnCXXNestedNameSpecifier(Scope *S,
5374 NestedNameSpecInfo &IdInfo,
5375 bool EnteringContext,
5376 CXXScopeSpec &SS,
5377 bool ErrorRecoveryLookup = false,
5378 bool *IsCorrectedToColon = nullptr,
5379 bool OnlyNamespace = false);
5380
5381 ExprResult ActOnDecltypeExpression(Expr *E);
5382
5383 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5384 const DeclSpec &DS,
5385 SourceLocation ColonColonLoc);
5386
5387 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5388 NestedNameSpecInfo &IdInfo,
5389 bool EnteringContext);
5390
5391 /// \brief The parser has parsed a nested-name-specifier
5392 /// 'template[opt] template-name < template-args >::'.
5393 ///
5394 /// \param S The scope in which this nested-name-specifier occurs.
5395 ///
5396 /// \param SS The nested-name-specifier, which is both an input
5397 /// parameter (the nested-name-specifier before this type) and an
5398 /// output parameter (containing the full nested-name-specifier,
5399 /// including this new type).
5400 ///
5401 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5402 /// \param TemplateName the template name.
5403 /// \param TemplateNameLoc The location of the template name.
5404 /// \param LAngleLoc The location of the opening angle bracket ('<').
5405 /// \param TemplateArgs The template arguments.
5406 /// \param RAngleLoc The location of the closing angle bracket ('>').
5407 /// \param CCLoc The location of the '::'.
5408 ///
5409 /// \param EnteringContext Whether we're entering the context of the
5410 /// nested-name-specifier.
5411 ///
5412 ///
5413 /// \returns true if an error occurred, false otherwise.
5414 bool ActOnCXXNestedNameSpecifier(Scope *S,
5415 CXXScopeSpec &SS,
5416 SourceLocation TemplateKWLoc,
5417 TemplateTy TemplateName,
5418 SourceLocation TemplateNameLoc,
5419 SourceLocation LAngleLoc,
5420 ASTTemplateArgsPtr TemplateArgs,
5421 SourceLocation RAngleLoc,
5422 SourceLocation CCLoc,
5423 bool EnteringContext);
5424
5425 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5426 /// that the parser can use later to reconstruct the given
5427 /// nested-name-specifier.
5428 ///
5429 /// \param SS A nested-name-specifier.
5430 ///
5431 /// \returns A pointer containing all of the information in the
5432 /// nested-name-specifier \p SS.
5433 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5434
5435 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5436 /// the nested-name-specifier structure.
5437 ///
5438 /// \param Annotation The annotation pointer, produced by
5439 /// \c SaveNestedNameSpecifierAnnotation().
5440 ///
5441 /// \param AnnotationRange The source range corresponding to the annotation.
5442 ///
5443 /// \param SS The nested-name-specifier that will be updated with the contents
5444 /// of the annotation pointer.
5445 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5446 SourceRange AnnotationRange,
5447 CXXScopeSpec &SS);
5448
5449 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5450
5451 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5452 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5453 /// After this method is called, according to [C++ 3.4.3p3], names should be
5454 /// looked up in the declarator-id's scope, until the declarator is parsed and
5455 /// ActOnCXXExitDeclaratorScope is called.
5456 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5457 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5458
5459 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5460 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5461 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5462 /// Used to indicate that names should revert to being looked up in the
5463 /// defining scope.
5464 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5465
5466 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5467 /// initializer for the declaration 'Dcl'.
5468 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5469 /// static data member of class X, names should be looked up in the scope of
5470 /// class X.
5471 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5472
5473 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5474 /// initializer for the declaration 'Dcl'.
5475 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5476
5477 /// \brief Create a new lambda closure type.
5478 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5479 TypeSourceInfo *Info,
5480 bool KnownDependent,
5481 LambdaCaptureDefault CaptureDefault);
5482
5483 /// \brief Start the definition of a lambda expression.
5484 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5485 SourceRange IntroducerRange,
5486 TypeSourceInfo *MethodType,
5487 SourceLocation EndLoc,
5488 ArrayRef<ParmVarDecl *> Params,
5489 bool IsConstexprSpecified);
5490
5491 /// \brief Endow the lambda scope info with the relevant properties.
5492 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5493 CXXMethodDecl *CallOperator,
5494 SourceRange IntroducerRange,
5495 LambdaCaptureDefault CaptureDefault,
5496 SourceLocation CaptureDefaultLoc,
5497 bool ExplicitParams,
5498 bool ExplicitResultType,
5499 bool Mutable);
5500
5501 /// \brief Perform initialization analysis of the init-capture and perform
5502 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5503 /// not being used to initialize a reference.
5504 ParsedType actOnLambdaInitCaptureInitialization(
5505 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5506 LambdaCaptureInitKind InitKind, Expr *&Init) {
5507 return ParsedType::make(buildLambdaInitCaptureInitialization(
5508 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5509 }
5510 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5511 IdentifierInfo *Id,
5512 bool DirectInit, Expr *&Init);
5513
5514 /// \brief Create a dummy variable within the declcontext of the lambda's
5515 /// call operator, for name lookup purposes for a lambda init capture.
5516 ///
5517 /// CodeGen handles emission of lambda captures, ignoring these dummy
5518 /// variables appropriately.
5519 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5520 QualType InitCaptureType,
5521 IdentifierInfo *Id,
5522 unsigned InitStyle, Expr *Init);
5523
5524 /// \brief Build the implicit field for an init-capture.
5525 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5526
5527 /// \brief Note that we have finished the explicit captures for the
5528 /// given lambda.
5529 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5530
5531 /// \brief Introduce the lambda parameters into scope.
5532 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5533
5534 /// \brief Deduce a block or lambda's return type based on the return
5535 /// statements present in the body.
5536 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5537
5538 /// ActOnStartOfLambdaDefinition - This is called just before we start
5539 /// parsing the body of a lambda; it analyzes the explicit captures and
5540 /// arguments, and sets up various data-structures for the body of the
5541 /// lambda.
5542 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5543 Declarator &ParamInfo, Scope *CurScope);
5544
5545 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5546 /// is invoked to pop the information about the lambda.
5547 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5548 bool IsInstantiation = false);
5549
5550 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5551 /// was successfully completed.
5552 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5553 Scope *CurScope);
5554
5555 /// \brief Does copying/destroying the captured variable have side effects?
5556 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5557
5558 /// \brief Diagnose if an explicit lambda capture is unused.
5559 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5560
5561 /// \brief Complete a lambda-expression having processed and attached the
5562 /// lambda body.
5563 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5564 sema::LambdaScopeInfo *LSI);
5565
5566 /// Get the return type to use for a lambda's conversion function(s) to
5567 /// function pointer type, given the type of the call operator.
5568 QualType
5569 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
5570
5571 /// \brief Define the "body" of the conversion from a lambda object to a
5572 /// function pointer.
5573 ///
5574 /// This routine doesn't actually define a sensible body; rather, it fills
5575 /// in the initialization expression needed to copy the lambda object into
5576 /// the block, and IR generation actually generates the real body of the
5577 /// block pointer conversion.
5578 void DefineImplicitLambdaToFunctionPointerConversion(
5579 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5580
5581 /// \brief Define the "body" of the conversion from a lambda object to a
5582 /// block pointer.
5583 ///
5584 /// This routine doesn't actually define a sensible body; rather, it fills
5585 /// in the initialization expression needed to copy the lambda object into
5586 /// the block, and IR generation actually generates the real body of the
5587 /// block pointer conversion.
5588 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5589 CXXConversionDecl *Conv);
5590
5591 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5592 SourceLocation ConvLocation,
5593 CXXConversionDecl *Conv,
5594 Expr *Src);
5595
5596 // ParseObjCStringLiteral - Parse Objective-C string literals.
5597 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5598 ArrayRef<Expr *> Strings);
5599
5600 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5601
5602 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5603 /// numeric literal expression. Type of the expression will be "NSNumber *"
5604 /// or "id" if NSNumber is unavailable.
5605 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5606 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5607 bool Value);
5608 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5609
5610 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5611 /// '@' prefixed parenthesized expression. The type of the expression will
5612 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5613 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5614 /// "const char *" or C structure with attribute 'objc_boxable'.
5615 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5616
5617 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5618 Expr *IndexExpr,
5619 ObjCMethodDecl *getterMethod,
5620 ObjCMethodDecl *setterMethod);
5621
5622 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5623 MutableArrayRef<ObjCDictionaryElement> Elements);
5624
5625 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5626 TypeSourceInfo *EncodedTypeInfo,
5627 SourceLocation RParenLoc);
5628 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5629 CXXConversionDecl *Method,
5630 bool HadMultipleCandidates);
5631
5632 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5633 SourceLocation EncodeLoc,
5634 SourceLocation LParenLoc,
5635 ParsedType Ty,
5636 SourceLocation RParenLoc);
5637
5638 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5639 ExprResult ParseObjCSelectorExpression(Selector Sel,
5640 SourceLocation AtLoc,
5641 SourceLocation SelLoc,
5642 SourceLocation LParenLoc,
5643 SourceLocation RParenLoc,
5644 bool WarnMultipleSelectors);
5645
5646 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5647 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5648 SourceLocation AtLoc,
5649 SourceLocation ProtoLoc,
5650 SourceLocation LParenLoc,
5651 SourceLocation ProtoIdLoc,
5652 SourceLocation RParenLoc);
5653
5654 //===--------------------------------------------------------------------===//
5655 // C++ Declarations
5656 //
5657 Decl *ActOnStartLinkageSpecification(Scope *S,
5658 SourceLocation ExternLoc,
5659 Expr *LangStr,
5660 SourceLocation LBraceLoc);
5661 Decl *ActOnFinishLinkageSpecification(Scope *S,
5662 Decl *LinkageSpec,
5663 SourceLocation RBraceLoc);
5664
5665
5666 //===--------------------------------------------------------------------===//
5667 // C++ Classes
5668 //
5669 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5670 const CXXScopeSpec *SS = nullptr);
5671 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5672
5673 bool ActOnAccessSpecifier(AccessSpecifier Access,
5674 SourceLocation ASLoc,
5675 SourceLocation ColonLoc,
5676 AttributeList *Attrs = nullptr);
5677
5678 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5679 Declarator &D,
5680 MultiTemplateParamsArg TemplateParameterLists,
5681 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5682 InClassInitStyle InitStyle);
5683
5684 void ActOnStartCXXInClassMemberInitializer();
5685 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5686 SourceLocation EqualLoc,
5687 Expr *Init);
5688
5689 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5690 Scope *S,
5691 CXXScopeSpec &SS,
5692 IdentifierInfo *MemberOrBase,
5693 ParsedType TemplateTypeTy,
5694 const DeclSpec &DS,
5695 SourceLocation IdLoc,
5696 SourceLocation LParenLoc,
5697 ArrayRef<Expr *> Args,
5698 SourceLocation RParenLoc,
5699 SourceLocation EllipsisLoc);
5700
5701 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5702 Scope *S,
5703 CXXScopeSpec &SS,
5704 IdentifierInfo *MemberOrBase,
5705 ParsedType TemplateTypeTy,
5706 const DeclSpec &DS,
5707 SourceLocation IdLoc,
5708 Expr *InitList,
5709 SourceLocation EllipsisLoc);
5710
5711 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5712 Scope *S,
5713 CXXScopeSpec &SS,
5714 IdentifierInfo *MemberOrBase,
5715 ParsedType TemplateTypeTy,
5716 const DeclSpec &DS,
5717 SourceLocation IdLoc,
5718 Expr *Init,
5719 SourceLocation EllipsisLoc);
5720
5721 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5722 Expr *Init,
5723 SourceLocation IdLoc);
5724
5725 MemInitResult BuildBaseInitializer(QualType BaseType,
5726 TypeSourceInfo *BaseTInfo,
5727 Expr *Init,
5728 CXXRecordDecl *ClassDecl,
5729 SourceLocation EllipsisLoc);
5730
5731 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5732 Expr *Init,
5733 CXXRecordDecl *ClassDecl);
5734
5735 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5736 CXXCtorInitializer *Initializer);
5737
5738 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5739 ArrayRef<CXXCtorInitializer *> Initializers = None);
5740
5741 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5742
5743
5744 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5745 /// mark all the non-trivial destructors of its members and bases as
5746 /// referenced.
5747 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5748 CXXRecordDecl *Record);
5749
5750 /// \brief The list of classes whose vtables have been used within
5751 /// this translation unit, and the source locations at which the
5752 /// first use occurred.
5753 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5754
5755 /// \brief The list of vtables that are required but have not yet been
5756 /// materialized.
5757 SmallVector<VTableUse, 16> VTableUses;
5758
5759 /// \brief The set of classes whose vtables have been used within
5760 /// this translation unit, and a bit that will be true if the vtable is
5761 /// required to be emitted (otherwise, it should be emitted only if needed
5762 /// by code generation).
5763 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5764
5765 /// \brief Load any externally-stored vtable uses.
5766 void LoadExternalVTableUses();
5767
5768 /// \brief Note that the vtable for the given class was used at the
5769 /// given location.
5770 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5771 bool DefinitionRequired = false);
5772
5773 /// \brief Mark the exception specifications of all virtual member functions
5774 /// in the given class as needed.
5775 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5776 const CXXRecordDecl *RD);
5777
5778 /// MarkVirtualMembersReferenced - Will mark all members of the given
5779 /// CXXRecordDecl referenced.
5780 void MarkVirtualMembersReferenced(SourceLocation Loc,
5781 const CXXRecordDecl *RD);
5782
5783 /// \brief Define all of the vtables that have been used in this
5784 /// translation unit and reference any virtual members used by those
5785 /// vtables.
5786 ///
5787 /// \returns true if any work was done, false otherwise.
5788 bool DefineUsedVTables();
5789
5790 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5791
5792 void ActOnMemInitializers(Decl *ConstructorDecl,
5793 SourceLocation ColonLoc,
5794 ArrayRef<CXXCtorInitializer*> MemInits,
5795 bool AnyErrors);
5796
5797 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5798 /// ensure that referenceDLLExportedClassMethods is called some point later
5799 /// when all outer classes of Class are complete.
5800 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5801
5802 void referenceDLLExportedClassMethods();
5803
5804 void propagateDLLAttrToBaseClassTemplate(
5805 CXXRecordDecl *Class, Attr *ClassAttr,
5806 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5807 SourceLocation BaseLoc);
5808
5809 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5810
5811 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5812 /// conditions that are needed for the attribute to have an effect.
5813 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5814
5815 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5816 Decl *TagDecl,
5817 SourceLocation LBrac,
5818 SourceLocation RBrac,
5819 AttributeList *AttrList);
5820 void ActOnFinishCXXMemberDecls();
5821 void ActOnFinishCXXNonNestedClass(Decl *D);
5822
5823 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5824 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5825 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5826 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5827 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5828 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5829 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5830 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5831 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5832 CachedTokens &Toks);
5833 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5834 bool IsInsideALocalClassWithinATemplateFunction();
5835
5836 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5837 Expr *AssertExpr,
5838 Expr *AssertMessageExpr,
5839 SourceLocation RParenLoc);
5840 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5841 Expr *AssertExpr,
5842 StringLiteral *AssertMessageExpr,
5843 SourceLocation RParenLoc,
5844 bool Failed);
5845
5846 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5847 SourceLocation FriendLoc,
5848 TypeSourceInfo *TSInfo);
5849 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5850 MultiTemplateParamsArg TemplateParams);
5851 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5852 MultiTemplateParamsArg TemplateParams);
5853
5854 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5855 StorageClass& SC);
5856 void CheckConstructor(CXXConstructorDecl *Constructor);
5857 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5858 StorageClass& SC);
5859 bool CheckDestructor(CXXDestructorDecl *Destructor);
5860 void CheckConversionDeclarator(Declarator &D, QualType &R,
5861 StorageClass& SC);
5862 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5863 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5864 StorageClass &SC);
5865 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5866
5867 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5868 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5869 const FunctionProtoType *T);
5870 void CheckDelayedMemberExceptionSpecs();
5871
5872 //===--------------------------------------------------------------------===//
5873 // C++ Derived Classes
5874 //
5875
5876 /// ActOnBaseSpecifier - Parsed a base specifier
5877 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5878 SourceRange SpecifierRange,
5879 bool Virtual, AccessSpecifier Access,
5880 TypeSourceInfo *TInfo,
5881 SourceLocation EllipsisLoc);
5882
5883 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5884 SourceRange SpecifierRange,
5885 ParsedAttributes &Attrs,
5886 bool Virtual, AccessSpecifier Access,
5887 ParsedType basetype,
5888 SourceLocation BaseLoc,
5889 SourceLocation EllipsisLoc);
5890
5891 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5892 MutableArrayRef<CXXBaseSpecifier *> Bases);
5893 void ActOnBaseSpecifiers(Decl *ClassDecl,
5894 MutableArrayRef<CXXBaseSpecifier *> Bases);
5895
5896 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5897 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5898 CXXBasePaths &Paths);
5899
5900 // FIXME: I don't like this name.
5901 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5902
5903 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5904 SourceLocation Loc, SourceRange Range,
5905 CXXCastPath *BasePath = nullptr,
5906 bool IgnoreAccess = false);
5907 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5908 unsigned InaccessibleBaseID,
5909 unsigned AmbigiousBaseConvID,
5910 SourceLocation Loc, SourceRange Range,
5911 DeclarationName Name,
5912 CXXCastPath *BasePath,
5913 bool IgnoreAccess = false);
5914
5915 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5916
5917 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5918 const CXXMethodDecl *Old);
5919
5920 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5921 /// covariant, according to C++ [class.virtual]p5.
5922 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5923 const CXXMethodDecl *Old);
5924
5925 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5926 /// spec is a subset of base spec.
5927 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5928 const CXXMethodDecl *Old);
5929
5930 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5931
5932 /// CheckOverrideControl - Check C++11 override control semantics.
5933 void CheckOverrideControl(NamedDecl *D);
5934
5935 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5936 /// not used in the declaration of an overriding method.
5937 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5938
5939 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5940 /// overrides a virtual member function marked 'final', according to
5941 /// C++11 [class.virtual]p4.
5942 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5943 const CXXMethodDecl *Old);
5944
5945
5946 //===--------------------------------------------------------------------===//
5947 // C++ Access Control
5948 //
5949
5950 enum AccessResult {
5951 AR_accessible,
5952 AR_inaccessible,
5953 AR_dependent,
5954 AR_delayed
5955 };
5956
5957 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5958 NamedDecl *PrevMemberDecl,
5959 AccessSpecifier LexicalAS);
5960
5961 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5962 DeclAccessPair FoundDecl);
5963 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5964 DeclAccessPair FoundDecl);
5965 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5966 SourceRange PlacementRange,
5967 CXXRecordDecl *NamingClass,
5968 DeclAccessPair FoundDecl,
5969 bool Diagnose = true);
5970 AccessResult CheckConstructorAccess(SourceLocation Loc,
5971 CXXConstructorDecl *D,
5972 DeclAccessPair FoundDecl,
5973 const InitializedEntity &Entity,
5974 bool IsCopyBindingRefToTemp = false);
5975 AccessResult CheckConstructorAccess(SourceLocation Loc,
5976 CXXConstructorDecl *D,
5977 DeclAccessPair FoundDecl,
5978 const InitializedEntity &Entity,
5979 const PartialDiagnostic &PDiag);
5980 AccessResult CheckDestructorAccess(SourceLocation Loc,
5981 CXXDestructorDecl *Dtor,
5982 const PartialDiagnostic &PDiag,
5983 QualType objectType = QualType());
5984 AccessResult CheckFriendAccess(NamedDecl *D);
5985 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5986 CXXRecordDecl *NamingClass,
5987 DeclAccessPair Found);
5988 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5989 Expr *ObjectExpr,
5990 Expr *ArgExpr,
5991 DeclAccessPair FoundDecl);
5992 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5993 DeclAccessPair FoundDecl);
5994 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5995 QualType Base, QualType Derived,
5996 const CXXBasePath &Path,
5997 unsigned DiagID,
5998 bool ForceCheck = false,
5999 bool ForceUnprivileged = false);
6000 void CheckLookupAccess(const LookupResult &R);
6001 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
6002 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
6003 AccessSpecifier access,
6004 QualType objectType);
6005
6006 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6007 const MultiLevelTemplateArgumentList &TemplateArgs);
6008 void PerformDependentDiagnostics(const DeclContext *Pattern,
6009 const MultiLevelTemplateArgumentList &TemplateArgs);
6010
6011 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6012
6013 /// \brief When true, access checking violations are treated as SFINAE
6014 /// failures rather than hard errors.
6015 bool AccessCheckingSFINAE;
6016
6017 enum AbstractDiagSelID {
6018 AbstractNone = -1,
6019 AbstractReturnType,
6020 AbstractParamType,
6021 AbstractVariableType,
6022 AbstractFieldType,
6023 AbstractIvarType,
6024 AbstractSynthesizedIvarType,
6025 AbstractArrayType
6026 };
6027
6028 bool isAbstractType(SourceLocation Loc, QualType T);
6029 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6030 TypeDiagnoser &Diagnoser);
6031 template <typename... Ts>
6032 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6033 const Ts &...Args) {
6034 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6035 return RequireNonAbstractType(Loc, T, Diagnoser);
6036 }
6037
6038 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6039
6040 //===--------------------------------------------------------------------===//
6041 // C++ Overloaded Operators [C++ 13.5]
6042 //
6043
6044 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6045
6046 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6047
6048 //===--------------------------------------------------------------------===//
6049 // C++ Templates [C++ 14]
6050 //
6051 void FilterAcceptableTemplateNames(LookupResult &R,
6052 bool AllowFunctionTemplates = true);
6053 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6054 bool AllowFunctionTemplates = true);
6055
6056 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6057 QualType ObjectType, bool EnteringContext,
6058 bool &MemberOfUnknownSpecialization);
6059
6060 TemplateNameKind isTemplateName(Scope *S,
6061 CXXScopeSpec &SS,
6062 bool hasTemplateKeyword,
6063 UnqualifiedId &Name,
6064 ParsedType ObjectType,
6065 bool EnteringContext,
6066 TemplateTy &Template,
6067 bool &MemberOfUnknownSpecialization);
6068
6069 /// Determine whether a particular identifier might be the name in a C++1z
6070 /// deduction-guide declaration.
6071 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6072 SourceLocation NameLoc,
6073 ParsedTemplateTy *Template = nullptr);
6074
6075 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6076 SourceLocation IILoc,
6077 Scope *S,
6078 const CXXScopeSpec *SS,
6079 TemplateTy &SuggestedTemplate,
6080 TemplateNameKind &SuggestedKind);
6081
6082 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6083 NamedDecl *Instantiation,
6084 bool InstantiatedFromMember,
6085 const NamedDecl *Pattern,
6086 const NamedDecl *PatternDef,
6087 TemplateSpecializationKind TSK,
6088 bool Complain = true);
6089
6090 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6091 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6092
6093 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6094 SourceLocation EllipsisLoc,
6095 SourceLocation KeyLoc,
6096 IdentifierInfo *ParamName,
6097 SourceLocation ParamNameLoc,
6098 unsigned Depth, unsigned Position,
6099 SourceLocation EqualLoc,
6100 ParsedType DefaultArg);
6101
6102 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6103 SourceLocation Loc);
6104 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6105
6106 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6107 unsigned Depth,
6108 unsigned Position,
6109 SourceLocation EqualLoc,
6110 Expr *DefaultArg);
6111 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6112 SourceLocation TmpLoc,
6113 TemplateParameterList *Params,
6114 SourceLocation EllipsisLoc,
6115 IdentifierInfo *ParamName,
6116 SourceLocation ParamNameLoc,
6117 unsigned Depth,
6118 unsigned Position,
6119 SourceLocation EqualLoc,
6120 ParsedTemplateArgument DefaultArg);
6121
6122 TemplateParameterList *
6123 ActOnTemplateParameterList(unsigned Depth,
6124 SourceLocation ExportLoc,
6125 SourceLocation TemplateLoc,
6126 SourceLocation LAngleLoc,
6127 ArrayRef<NamedDecl *> Params,
6128 SourceLocation RAngleLoc,
6129 Expr *RequiresClause);
6130
6131 /// \brief The context in which we are checking a template parameter list.
6132 enum TemplateParamListContext {
6133 TPC_ClassTemplate,
6134 TPC_VarTemplate,
6135 TPC_FunctionTemplate,
6136 TPC_ClassTemplateMember,
6137 TPC_FriendClassTemplate,
6138 TPC_FriendFunctionTemplate,
6139 TPC_FriendFunctionTemplateDefinition,
6140 TPC_TypeAliasTemplate
6141 };
6142
6143 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6144 TemplateParameterList *OldParams,
6145 TemplateParamListContext TPC);
6146 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6147 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6148 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6149 ArrayRef<TemplateParameterList *> ParamLists,
6150 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6151
6152 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6153 SourceLocation KWLoc, CXXScopeSpec &SS,
6154 IdentifierInfo *Name, SourceLocation NameLoc,
6155 AttributeList *Attr,
6156 TemplateParameterList *TemplateParams,
6157 AccessSpecifier AS,
6158 SourceLocation ModulePrivateLoc,
6159 SourceLocation FriendLoc,
6160 unsigned NumOuterTemplateParamLists,
6161 TemplateParameterList **OuterTemplateParamLists,
6162 SkipBodyInfo *SkipBody = nullptr);
6163
6164 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6165 QualType NTTPType,
6166 SourceLocation Loc);
6167
6168 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6169 TemplateArgumentListInfo &Out);
6170
6171 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6172
6173 void NoteAllFoundTemplates(TemplateName Name);
6174
6175 QualType CheckTemplateIdType(TemplateName Template,
6176 SourceLocation TemplateLoc,
6177 TemplateArgumentListInfo &TemplateArgs);
6178
6179 TypeResult
6180 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6181 TemplateTy Template, IdentifierInfo *TemplateII,
6182 SourceLocation TemplateIILoc,
6183 SourceLocation LAngleLoc,
6184 ASTTemplateArgsPtr TemplateArgs,
6185 SourceLocation RAngleLoc,
6186 bool IsCtorOrDtorName = false,
6187 bool IsClassName = false);
6188
6189 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6190 /// such as \c class T::template apply<U>.
6191 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6192 TypeSpecifierType TagSpec,
6193 SourceLocation TagLoc,
6194 CXXScopeSpec &SS,
6195 SourceLocation TemplateKWLoc,
6196 TemplateTy TemplateD,
6197 SourceLocation TemplateLoc,
6198 SourceLocation LAngleLoc,
6199 ASTTemplateArgsPtr TemplateArgsIn,
6200 SourceLocation RAngleLoc);
6201
6202 DeclResult ActOnVarTemplateSpecialization(
6203 Scope *S, Declarator &D, TypeSourceInfo *DI,
6204 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6205 StorageClass SC, bool IsPartialSpecialization);
6206
6207 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6208 SourceLocation TemplateLoc,
6209 SourceLocation TemplateNameLoc,
6210 const TemplateArgumentListInfo &TemplateArgs);
6211
6212 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6213 const DeclarationNameInfo &NameInfo,
6214 VarTemplateDecl *Template,
6215 SourceLocation TemplateLoc,
6216 const TemplateArgumentListInfo *TemplateArgs);
6217
6218 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6219 SourceLocation TemplateKWLoc,
6220 LookupResult &R,
6221 bool RequiresADL,
6222 const TemplateArgumentListInfo *TemplateArgs);
6223
6224 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6225 SourceLocation TemplateKWLoc,
6226 const DeclarationNameInfo &NameInfo,
6227 const TemplateArgumentListInfo *TemplateArgs);
6228
6229 TemplateNameKind ActOnDependentTemplateName(
6230 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6231 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6232 TemplateTy &Template, bool AllowInjectedClassName = false);
6233
6234 DeclResult
6235 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6236 SourceLocation KWLoc,
6237 SourceLocation ModulePrivateLoc,
6238 TemplateIdAnnotation &TemplateId,
6239 AttributeList *Attr,
6240 MultiTemplateParamsArg TemplateParameterLists,
6241 SkipBodyInfo *SkipBody = nullptr);
6242
6243 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6244 TemplateDecl *PrimaryTemplate,
6245 unsigned NumExplicitArgs,
6246 ArrayRef<TemplateArgument> Args);
6247 void CheckTemplatePartialSpecialization(
6248 ClassTemplatePartialSpecializationDecl *Partial);
6249 void CheckTemplatePartialSpecialization(
6250 VarTemplatePartialSpecializationDecl *Partial);
6251
6252 Decl *ActOnTemplateDeclarator(Scope *S,
6253 MultiTemplateParamsArg TemplateParameterLists,
6254 Declarator &D);
6255
6256 bool
6257 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6258 TemplateSpecializationKind NewTSK,
6259 NamedDecl *PrevDecl,
6260 TemplateSpecializationKind PrevTSK,
6261 SourceLocation PrevPtOfInstantiation,
6262 bool &SuppressNew);
6263
6264 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6265 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6266 LookupResult &Previous);
6267
6268 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6269 TemplateArgumentListInfo *ExplicitTemplateArgs,
6270 LookupResult &Previous);
6271 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6272 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6273
6274 DeclResult
6275 ActOnExplicitInstantiation(Scope *S,
6276 SourceLocation ExternLoc,
6277 SourceLocation TemplateLoc,
6278 unsigned TagSpec,
6279 SourceLocation KWLoc,
6280 const CXXScopeSpec &SS,
6281 TemplateTy Template,
6282 SourceLocation TemplateNameLoc,
6283 SourceLocation LAngleLoc,
6284 ASTTemplateArgsPtr TemplateArgs,
6285 SourceLocation RAngleLoc,
6286 AttributeList *Attr);
6287
6288 DeclResult
6289 ActOnExplicitInstantiation(Scope *S,
6290 SourceLocation ExternLoc,
6291 SourceLocation TemplateLoc,
6292 unsigned TagSpec,
6293 SourceLocation KWLoc,
6294 CXXScopeSpec &SS,
6295 IdentifierInfo *Name,
6296 SourceLocation NameLoc,
6297 AttributeList *Attr);
6298
6299 DeclResult ActOnExplicitInstantiation(Scope *S,
6300 SourceLocation ExternLoc,
6301 SourceLocation TemplateLoc,
6302 Declarator &D);
6303
6304 TemplateArgumentLoc
6305 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6306 SourceLocation TemplateLoc,
6307 SourceLocation RAngleLoc,
6308 Decl *Param,
6309 SmallVectorImpl<TemplateArgument>
6310 &Converted,
6311 bool &HasDefaultArg);
6312
6313 /// \brief Specifies the context in which a particular template
6314 /// argument is being checked.
6315 enum CheckTemplateArgumentKind {
6316 /// \brief The template argument was specified in the code or was
6317 /// instantiated with some deduced template arguments.
6318 CTAK_Specified,
6319
6320 /// \brief The template argument was deduced via template argument
6321 /// deduction.
6322 CTAK_Deduced,
6323
6324 /// \brief The template argument was deduced from an array bound
6325 /// via template argument deduction.
6326 CTAK_DeducedFromArrayBound
6327 };
6328
6329 bool CheckTemplateArgument(NamedDecl *Param,
6330 TemplateArgumentLoc &Arg,
6331 NamedDecl *Template,
6332 SourceLocation TemplateLoc,
6333 SourceLocation RAngleLoc,
6334 unsigned ArgumentPackIndex,
6335 SmallVectorImpl<TemplateArgument> &Converted,
6336 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6337
6338 /// \brief Check that the given template arguments can be be provided to
6339 /// the given template, converting the arguments along the way.
6340 ///
6341 /// \param Template The template to which the template arguments are being
6342 /// provided.
6343 ///
6344 /// \param TemplateLoc The location of the template name in the source.
6345 ///
6346 /// \param TemplateArgs The list of template arguments. If the template is
6347 /// a template template parameter, this function may extend the set of
6348 /// template arguments to also include substituted, defaulted template
6349 /// arguments.
6350 ///
6351 /// \param PartialTemplateArgs True if the list of template arguments is
6352 /// intentionally partial, e.g., because we're checking just the initial
6353 /// set of template arguments.
6354 ///
6355 /// \param Converted Will receive the converted, canonicalized template
6356 /// arguments.
6357 ///
6358 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6359 /// contain the converted forms of the template arguments as written.
6360 /// Otherwise, \p TemplateArgs will not be modified.
6361 ///
6362 /// \returns true if an error occurred, false otherwise.
6363 bool CheckTemplateArgumentList(TemplateDecl *Template,
6364 SourceLocation TemplateLoc,
6365 TemplateArgumentListInfo &TemplateArgs,
6366 bool PartialTemplateArgs,
6367 SmallVectorImpl<TemplateArgument> &Converted,
6368 bool UpdateArgsWithConversions = true);
6369
6370 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6371 TemplateArgumentLoc &Arg,
6372 SmallVectorImpl<TemplateArgument> &Converted);
6373
6374 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6375 TypeSourceInfo *Arg);
6376 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6377 QualType InstantiatedParamType, Expr *Arg,
6378 TemplateArgument &Converted,
6379 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6380 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6381 TemplateArgumentLoc &Arg,
6382 unsigned ArgumentPackIndex);
6383
6384 ExprResult
6385 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6386 QualType ParamType,
6387 SourceLocation Loc);
6388 ExprResult
6389 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6390 SourceLocation Loc);
6391
6392 /// \brief Enumeration describing how template parameter lists are compared
6393 /// for equality.
6394 enum TemplateParameterListEqualKind {
6395 /// \brief We are matching the template parameter lists of two templates
6396 /// that might be redeclarations.
6397 ///
6398 /// \code
6399 /// template<typename T> struct X;
6400 /// template<typename T> struct X;
6401 /// \endcode
6402 TPL_TemplateMatch,
6403
6404 /// \brief We are matching the template parameter lists of two template
6405 /// template parameters as part of matching the template parameter lists
6406 /// of two templates that might be redeclarations.
6407 ///
6408 /// \code
6409 /// template<template<int I> class TT> struct X;
6410 /// template<template<int Value> class Other> struct X;
6411 /// \endcode
6412 TPL_TemplateTemplateParmMatch,
6413
6414 /// \brief We are matching the template parameter lists of a template
6415 /// template argument against the template parameter lists of a template
6416 /// template parameter.
6417 ///
6418 /// \code
6419 /// template<template<int Value> class Metafun> struct X;
6420 /// template<int Value> struct integer_c;
6421 /// X<integer_c> xic;
6422 /// \endcode
6423 TPL_TemplateTemplateArgumentMatch
6424 };
6425
6426 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6427 TemplateParameterList *Old,
6428 bool Complain,
6429 TemplateParameterListEqualKind Kind,
6430 SourceLocation TemplateArgLoc
6431 = SourceLocation());
6432
6433 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6434
6435 /// \brief Called when the parser has parsed a C++ typename
6436 /// specifier, e.g., "typename T::type".
6437 ///
6438 /// \param S The scope in which this typename type occurs.
6439 /// \param TypenameLoc the location of the 'typename' keyword
6440 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6441 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6442 /// \param IdLoc the location of the identifier.
6443 TypeResult
6444 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6445 const CXXScopeSpec &SS, const IdentifierInfo &II,
6446 SourceLocation IdLoc);
6447
6448 /// \brief Called when the parser has parsed a C++ typename
6449 /// specifier that ends in a template-id, e.g.,
6450 /// "typename MetaFun::template apply<T1, T2>".
6451 ///
6452 /// \param S The scope in which this typename type occurs.
6453 /// \param TypenameLoc the location of the 'typename' keyword
6454 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6455 /// \param TemplateLoc the location of the 'template' keyword, if any.
6456 /// \param TemplateName The template name.
6457 /// \param TemplateII The identifier used to name the template.
6458 /// \param TemplateIILoc The location of the template name.
6459 /// \param LAngleLoc The location of the opening angle bracket ('<').
6460 /// \param TemplateArgs The template arguments.
6461 /// \param RAngleLoc The location of the closing angle bracket ('>').
6462 TypeResult
6463 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6464 const CXXScopeSpec &SS,
6465 SourceLocation TemplateLoc,
6466 TemplateTy TemplateName,
6467 IdentifierInfo *TemplateII,
6468 SourceLocation TemplateIILoc,
6469 SourceLocation LAngleLoc,
6470 ASTTemplateArgsPtr TemplateArgs,
6471 SourceLocation RAngleLoc);
6472
6473 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6474 SourceLocation KeywordLoc,
6475 NestedNameSpecifierLoc QualifierLoc,
6476 const IdentifierInfo &II,
6477 SourceLocation IILoc);
6478
6479 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6480 SourceLocation Loc,
6481 DeclarationName Name);
6482 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6483
6484 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6485 bool RebuildTemplateParamsInCurrentInstantiation(
6486 TemplateParameterList *Params);
6487
6488 std::string
6489 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6490 const TemplateArgumentList &Args);
6491
6492 std::string
6493 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6494 const TemplateArgument *Args,
6495 unsigned NumArgs);
6496
6497 //===--------------------------------------------------------------------===//
6498 // C++ Variadic Templates (C++0x [temp.variadic])
6499 //===--------------------------------------------------------------------===//
6500
6501 /// Determine whether an unexpanded parameter pack might be permitted in this
6502 /// location. Useful for error recovery.
6503 bool isUnexpandedParameterPackPermitted();
6504
6505 /// \brief The context in which an unexpanded parameter pack is
6506 /// being diagnosed.
6507 ///
6508 /// Note that the values of this enumeration line up with the first
6509 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6510 enum UnexpandedParameterPackContext {
6511 /// \brief An arbitrary expression.
6512 UPPC_Expression = 0,
6513
6514 /// \brief The base type of a class type.
6515 UPPC_BaseType,
6516
6517 /// \brief The type of an arbitrary declaration.
6518 UPPC_DeclarationType,
6519
6520 /// \brief The type of a data member.
6521 UPPC_DataMemberType,
6522
6523 /// \brief The size of a bit-field.
6524 UPPC_BitFieldWidth,
6525
6526 /// \brief The expression in a static assertion.
6527 UPPC_StaticAssertExpression,
6528
6529 /// \brief The fixed underlying type of an enumeration.
6530 UPPC_FixedUnderlyingType,
6531
6532 /// \brief The enumerator value.
6533 UPPC_EnumeratorValue,
6534
6535 /// \brief A using declaration.
6536 UPPC_UsingDeclaration,
6537
6538 /// \brief A friend declaration.
6539 UPPC_FriendDeclaration,
6540
6541 /// \brief A declaration qualifier.
6542 UPPC_DeclarationQualifier,
6543
6544 /// \brief An initializer.
6545 UPPC_Initializer,
6546
6547 /// \brief A default argument.
6548 UPPC_DefaultArgument,
6549
6550 /// \brief The type of a non-type template parameter.
6551 UPPC_NonTypeTemplateParameterType,
6552
6553 /// \brief The type of an exception.
6554 UPPC_ExceptionType,
6555
6556 /// \brief Partial specialization.
6557 UPPC_PartialSpecialization,
6558
6559 /// \brief Microsoft __if_exists.
6560 UPPC_IfExists,
6561
6562 /// \brief Microsoft __if_not_exists.
6563 UPPC_IfNotExists,
6564
6565 /// \brief Lambda expression.
6566 UPPC_Lambda,
6567
6568 /// \brief Block expression,
6569 UPPC_Block
6570 };
6571
6572 /// \brief Diagnose unexpanded parameter packs.
6573 ///
6574 /// \param Loc The location at which we should emit the diagnostic.
6575 ///
6576 /// \param UPPC The context in which we are diagnosing unexpanded
6577 /// parameter packs.
6578 ///
6579 /// \param Unexpanded the set of unexpanded parameter packs.
6580 ///
6581 /// \returns true if an error occurred, false otherwise.
6582 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6583 UnexpandedParameterPackContext UPPC,
6584 ArrayRef<UnexpandedParameterPack> Unexpanded);
6585
6586 /// \brief If the given type contains an unexpanded parameter pack,
6587 /// diagnose the error.
6588 ///
6589 /// \param Loc The source location where a diagnostc should be emitted.
6590 ///
6591 /// \param T The type that is being checked for unexpanded parameter
6592 /// packs.
6593 ///
6594 /// \returns true if an error occurred, false otherwise.
6595 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6596 UnexpandedParameterPackContext UPPC);
6597
6598 /// \brief If the given expression contains an unexpanded parameter
6599 /// pack, diagnose the error.
6600 ///
6601 /// \param E The expression that is being checked for unexpanded
6602 /// parameter packs.
6603 ///
6604 /// \returns true if an error occurred, false otherwise.
6605 bool DiagnoseUnexpandedParameterPack(Expr *E,
6606 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6607
6608 /// \brief If the given nested-name-specifier contains an unexpanded
6609 /// parameter pack, diagnose the error.
6610 ///
6611 /// \param SS The nested-name-specifier that is being checked for
6612 /// unexpanded parameter packs.
6613 ///
6614 /// \returns true if an error occurred, false otherwise.
6615 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6616 UnexpandedParameterPackContext UPPC);
6617
6618 /// \brief If the given name contains an unexpanded parameter pack,
6619 /// diagnose the error.
6620 ///
6621 /// \param NameInfo The name (with source location information) that
6622 /// is being checked for unexpanded parameter packs.
6623 ///
6624 /// \returns true if an error occurred, false otherwise.
6625 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6626 UnexpandedParameterPackContext UPPC);
6627
6628 /// \brief If the given template name contains an unexpanded parameter pack,
6629 /// diagnose the error.
6630 ///
6631 /// \param Loc The location of the template name.
6632 ///
6633 /// \param Template The template name that is being checked for unexpanded
6634 /// parameter packs.
6635 ///
6636 /// \returns true if an error occurred, false otherwise.
6637 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6638 TemplateName Template,
6639 UnexpandedParameterPackContext UPPC);
6640
6641 /// \brief If the given template argument contains an unexpanded parameter
6642 /// pack, diagnose the error.
6643 ///
6644 /// \param Arg The template argument that is being checked for unexpanded
6645 /// parameter packs.
6646 ///
6647 /// \returns true if an error occurred, false otherwise.
6648 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6649 UnexpandedParameterPackContext UPPC);
6650
6651 /// \brief Collect the set of unexpanded parameter packs within the given
6652 /// template argument.
6653 ///
6654 /// \param Arg The template argument that will be traversed to find
6655 /// unexpanded parameter packs.
6656 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6657 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6658
6659 /// \brief Collect the set of unexpanded parameter packs within the given
6660 /// template argument.
6661 ///
6662 /// \param Arg The template argument that will be traversed to find
6663 /// unexpanded parameter packs.
6664 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6665 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6666
6667 /// \brief Collect the set of unexpanded parameter packs within the given
6668 /// type.
6669 ///
6670 /// \param T The type that will be traversed to find
6671 /// unexpanded parameter packs.
6672 void collectUnexpandedParameterPacks(QualType T,
6673 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6674
6675 /// \brief Collect the set of unexpanded parameter packs within the given
6676 /// type.
6677 ///
6678 /// \param TL The type that will be traversed to find
6679 /// unexpanded parameter packs.
6680 void collectUnexpandedParameterPacks(TypeLoc TL,
6681 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6682
6683 /// \brief Collect the set of unexpanded parameter packs within the given
6684 /// nested-name-specifier.
6685 ///
6686 /// \param NNS The nested-name-specifier that will be traversed to find
6687 /// unexpanded parameter packs.
6688 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6689 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6690
6691 /// \brief Collect the set of unexpanded parameter packs within the given
6692 /// name.
6693 ///
6694 /// \param NameInfo The name that will be traversed to find
6695 /// unexpanded parameter packs.
6696 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6697 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6698
6699 /// \brief Invoked when parsing a template argument followed by an
6700 /// ellipsis, which creates a pack expansion.
6701 ///
6702 /// \param Arg The template argument preceding the ellipsis, which
6703 /// may already be invalid.
6704 ///
6705 /// \param EllipsisLoc The location of the ellipsis.
6706 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6707 SourceLocation EllipsisLoc);
6708
6709 /// \brief Invoked when parsing a type followed by an ellipsis, which
6710 /// creates a pack expansion.
6711 ///
6712 /// \param Type The type preceding the ellipsis, which will become
6713 /// the pattern of the pack expansion.
6714 ///
6715 /// \param EllipsisLoc The location of the ellipsis.
6716 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6717
6718 /// \brief Construct a pack expansion type from the pattern of the pack
6719 /// expansion.
6720 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6721 SourceLocation EllipsisLoc,
6722 Optional<unsigned> NumExpansions);
6723
6724 /// \brief Construct a pack expansion type from the pattern of the pack
6725 /// expansion.
6726 QualType CheckPackExpansion(QualType Pattern,
6727 SourceRange PatternRange,
6728 SourceLocation EllipsisLoc,
6729 Optional<unsigned> NumExpansions);
6730
6731 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6732 /// creates a pack expansion.
6733 ///
6734 /// \param Pattern The expression preceding the ellipsis, which will become
6735 /// the pattern of the pack expansion.
6736 ///
6737 /// \param EllipsisLoc The location of the ellipsis.
6738 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6739
6740 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6741 /// creates a pack expansion.
6742 ///
6743 /// \param Pattern The expression preceding the ellipsis, which will become
6744 /// the pattern of the pack expansion.
6745 ///
6746 /// \param EllipsisLoc The location of the ellipsis.
6747 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6748 Optional<unsigned> NumExpansions);
6749
6750 /// \brief Determine whether we could expand a pack expansion with the
6751 /// given set of parameter packs into separate arguments by repeatedly
6752 /// transforming the pattern.
6753 ///
6754 /// \param EllipsisLoc The location of the ellipsis that identifies the
6755 /// pack expansion.
6756 ///
6757 /// \param PatternRange The source range that covers the entire pattern of
6758 /// the pack expansion.
6759 ///
6760 /// \param Unexpanded The set of unexpanded parameter packs within the
6761 /// pattern.
6762 ///
6763 /// \param ShouldExpand Will be set to \c true if the transformer should
6764 /// expand the corresponding pack expansions into separate arguments. When
6765 /// set, \c NumExpansions must also be set.
6766 ///
6767 /// \param RetainExpansion Whether the caller should add an unexpanded
6768 /// pack expansion after all of the expanded arguments. This is used
6769 /// when extending explicitly-specified template argument packs per
6770 /// C++0x [temp.arg.explicit]p9.
6771 ///
6772 /// \param NumExpansions The number of separate arguments that will be in
6773 /// the expanded form of the corresponding pack expansion. This is both an
6774 /// input and an output parameter, which can be set by the caller if the
6775 /// number of expansions is known a priori (e.g., due to a prior substitution)
6776 /// and will be set by the callee when the number of expansions is known.
6777 /// The callee must set this value when \c ShouldExpand is \c true; it may
6778 /// set this value in other cases.
6779 ///
6780 /// \returns true if an error occurred (e.g., because the parameter packs
6781 /// are to be instantiated with arguments of different lengths), false
6782 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6783 /// must be set.
6784 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6785 SourceRange PatternRange,
6786 ArrayRef<UnexpandedParameterPack> Unexpanded,
6787 const MultiLevelTemplateArgumentList &TemplateArgs,
6788 bool &ShouldExpand,
6789 bool &RetainExpansion,
6790 Optional<unsigned> &NumExpansions);
6791
6792 /// \brief Determine the number of arguments in the given pack expansion
6793 /// type.
6794 ///
6795 /// This routine assumes that the number of arguments in the expansion is
6796 /// consistent across all of the unexpanded parameter packs in its pattern.
6797 ///
6798 /// Returns an empty Optional if the type can't be expanded.
6799 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6800 const MultiLevelTemplateArgumentList &TemplateArgs);
6801
6802 /// \brief Determine whether the given declarator contains any unexpanded
6803 /// parameter packs.
6804 ///
6805 /// This routine is used by the parser to disambiguate function declarators
6806 /// with an ellipsis prior to the ')', e.g.,
6807 ///
6808 /// \code
6809 /// void f(T...);
6810 /// \endcode
6811 ///
6812 /// To determine whether we have an (unnamed) function parameter pack or
6813 /// a variadic function.
6814 ///
6815 /// \returns true if the declarator contains any unexpanded parameter packs,
6816 /// false otherwise.
6817 bool containsUnexpandedParameterPacks(Declarator &D);
6818
6819 /// \brief Returns the pattern of the pack expansion for a template argument.
6820 ///
6821 /// \param OrigLoc The template argument to expand.
6822 ///
6823 /// \param Ellipsis Will be set to the location of the ellipsis.
6824 ///
6825 /// \param NumExpansions Will be set to the number of expansions that will
6826 /// be generated from this pack expansion, if known a priori.
6827 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6828 TemplateArgumentLoc OrigLoc,
6829 SourceLocation &Ellipsis,
6830 Optional<unsigned> &NumExpansions) const;
6831
6832 /// Given a template argument that contains an unexpanded parameter pack, but
6833 /// which has already been substituted, attempt to determine the number of
6834 /// elements that will be produced once this argument is fully-expanded.
6835 ///
6836 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6837 /// avoid actually expanding the pack where possible.
6838 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6839
6840 //===--------------------------------------------------------------------===//
6841 // C++ Template Argument Deduction (C++ [temp.deduct])
6842 //===--------------------------------------------------------------------===//
6843
6844 /// Adjust the type \p ArgFunctionType to match the calling convention,
6845 /// noreturn, and optionally the exception specification of \p FunctionType.
6846 /// Deduction often wants to ignore these properties when matching function
6847 /// types.
6848 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6849 bool AdjustExceptionSpec = false);
6850
6851 /// \brief Describes the result of template argument deduction.
6852 ///
6853 /// The TemplateDeductionResult enumeration describes the result of
6854 /// template argument deduction, as returned from
6855 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6856 /// structure provides additional information about the results of
6857 /// template argument deduction, e.g., the deduced template argument
6858 /// list (if successful) or the specific template parameters or
6859 /// deduced arguments that were involved in the failure.
6860 enum TemplateDeductionResult {
6861 /// \brief Template argument deduction was successful.
6862 TDK_Success = 0,
6863 /// \brief The declaration was invalid; do nothing.
6864 TDK_Invalid,
6865 /// \brief Template argument deduction exceeded the maximum template
6866 /// instantiation depth (which has already been diagnosed).
6867 TDK_InstantiationDepth,
6868 /// \brief Template argument deduction did not deduce a value
6869 /// for every template parameter.
6870 TDK_Incomplete,
6871 /// \brief Template argument deduction produced inconsistent
6872 /// deduced values for the given template parameter.
6873 TDK_Inconsistent,
6874 /// \brief Template argument deduction failed due to inconsistent
6875 /// cv-qualifiers on a template parameter type that would
6876 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6877 /// but were given a non-const "X".
6878 TDK_Underqualified,
6879 /// \brief Substitution of the deduced template argument values
6880 /// resulted in an error.
6881 TDK_SubstitutionFailure,
6882 /// \brief After substituting deduced template arguments, a dependent
6883 /// parameter type did not match the corresponding argument.
6884 TDK_DeducedMismatch,
6885 /// \brief After substituting deduced template arguments, an element of
6886 /// a dependent parameter type did not match the corresponding element
6887 /// of the corresponding argument (when deducing from an initializer list).
6888 TDK_DeducedMismatchNested,
6889 /// \brief A non-depnedent component of the parameter did not match the
6890 /// corresponding component of the argument.
6891 TDK_NonDeducedMismatch,
6892 /// \brief When performing template argument deduction for a function
6893 /// template, there were too many call arguments.
6894 TDK_TooManyArguments,
6895 /// \brief When performing template argument deduction for a function
6896 /// template, there were too few call arguments.
6897 TDK_TooFewArguments,
6898 /// \brief The explicitly-specified template arguments were not valid
6899 /// template arguments for the given template.
6900 TDK_InvalidExplicitArguments,
6901 /// \brief Checking non-dependent argument conversions failed.
6902 TDK_NonDependentConversionFailure,
6903 /// \brief Deduction failed; that's all we know.
6904 TDK_MiscellaneousDeductionFailure,
6905 /// \brief CUDA Target attributes do not match.
6906 TDK_CUDATargetMismatch
6907 };
6908
6909 TemplateDeductionResult
6910 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6911 const TemplateArgumentList &TemplateArgs,
6912 sema::TemplateDeductionInfo &Info);
6913
6914 TemplateDeductionResult
6915 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6916 const TemplateArgumentList &TemplateArgs,
6917 sema::TemplateDeductionInfo &Info);
6918
6919 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6920 FunctionTemplateDecl *FunctionTemplate,
6921 TemplateArgumentListInfo &ExplicitTemplateArgs,
6922 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6923 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6924 sema::TemplateDeductionInfo &Info);
6925
6926 /// brief A function argument from which we performed template argument
6927 // deduction for a call.
6928 struct OriginalCallArg {
6929 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6930 unsigned ArgIdx, QualType OriginalArgType)
6931 : OriginalParamType(OriginalParamType),
6932 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6933 OriginalArgType(OriginalArgType) {}
6934
6935 QualType OriginalParamType;
6936 bool DecomposedParam;
6937 unsigned ArgIdx;
6938 QualType OriginalArgType;
6939 };
6940
6941 TemplateDeductionResult FinishTemplateArgumentDeduction(
6942 FunctionTemplateDecl *FunctionTemplate,
6943 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6944 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6945 sema::TemplateDeductionInfo &Info,
6946 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6947 bool PartialOverloading = false,
6948 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6949
6950 TemplateDeductionResult DeduceTemplateArguments(
6951 FunctionTemplateDecl *FunctionTemplate,
6952 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6953 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6954 bool PartialOverloading,
6955 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6956
6957 TemplateDeductionResult
6958 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6959 TemplateArgumentListInfo *ExplicitTemplateArgs,
6960 QualType ArgFunctionType,
6961 FunctionDecl *&Specialization,
6962 sema::TemplateDeductionInfo &Info,
6963 bool IsAddressOfFunction = false);
6964
6965 TemplateDeductionResult
6966 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6967 QualType ToType,
6968 CXXConversionDecl *&Specialization,
6969 sema::TemplateDeductionInfo &Info);
6970
6971 TemplateDeductionResult
6972 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6973 TemplateArgumentListInfo *ExplicitTemplateArgs,
6974 FunctionDecl *&Specialization,
6975 sema::TemplateDeductionInfo &Info,
6976 bool IsAddressOfFunction = false);
6977
6978 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6979 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6980 /// \brief Substitute Replacement for auto in TypeWithAuto
6981 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6982 QualType Replacement);
6983 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6984 /// \p Replacement. This does not retain any \c auto type sugar.
6985 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6986
6987 /// \brief Result type of DeduceAutoType.
6988 enum DeduceAutoResult {
6989 DAR_Succeeded,
6990 DAR_Failed,
6991 DAR_FailedAlreadyDiagnosed
6992 };
6993
6994 DeduceAutoResult
6995 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6996 Optional<unsigned> DependentDeductionDepth = None);
6997 DeduceAutoResult
6998 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6999 Optional<unsigned> DependentDeductionDepth = None);
7000 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7001 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7002 bool Diagnose = true);
7003
7004 /// \brief Declare implicit deduction guides for a class template if we've
7005 /// not already done so.
7006 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7007 SourceLocation Loc);
7008
7009 QualType DeduceTemplateSpecializationFromInitializer(
7010 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7011 const InitializationKind &Kind, MultiExprArg Init);
7012
7013 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7014 QualType Type, TypeSourceInfo *TSI,
7015 SourceRange Range, bool DirectInit,
7016 Expr *Init);
7017
7018 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7019
7020 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7021 SourceLocation ReturnLoc,
7022 Expr *&RetExpr, AutoType *AT);
7023
7024 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7025 FunctionTemplateDecl *FT2,
7026 SourceLocation Loc,
7027 TemplatePartialOrderingContext TPOC,
7028 unsigned NumCallArguments1,
7029 unsigned NumCallArguments2);
7030 UnresolvedSetIterator
7031 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7032 TemplateSpecCandidateSet &FailedCandidates,
7033 SourceLocation Loc,
7034 const PartialDiagnostic &NoneDiag,
7035 const PartialDiagnostic &AmbigDiag,
7036 const PartialDiagnostic &CandidateDiag,
7037 bool Complain = true, QualType TargetType = QualType());
7038
7039 ClassTemplatePartialSpecializationDecl *
7040 getMoreSpecializedPartialSpecialization(
7041 ClassTemplatePartialSpecializationDecl *PS1,
7042 ClassTemplatePartialSpecializationDecl *PS2,
7043 SourceLocation Loc);
7044
7045 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7046 sema::TemplateDeductionInfo &Info);
7047
7048 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7049 VarTemplatePartialSpecializationDecl *PS1,
7050 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7051
7052 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7053 sema::TemplateDeductionInfo &Info);
7054
7055 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7056 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7057
7058 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7059 bool OnlyDeduced,
7060 unsigned Depth,
7061 llvm::SmallBitVector &Used);
7062 void MarkDeducedTemplateParameters(
7063 const FunctionTemplateDecl *FunctionTemplate,
7064 llvm::SmallBitVector &Deduced) {
7065 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7066 }
7067 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7068 const FunctionTemplateDecl *FunctionTemplate,
7069 llvm::SmallBitVector &Deduced);
7070
7071 //===--------------------------------------------------------------------===//
7072 // C++ Template Instantiation
7073 //
7074
7075 MultiLevelTemplateArgumentList
7076 getTemplateInstantiationArgs(NamedDecl *D,
7077 const TemplateArgumentList *Innermost = nullptr,
7078 bool RelativeToPrimary = false,
7079 const FunctionDecl *Pattern = nullptr);
7080
7081 /// A context in which code is being synthesized (where a source location
7082 /// alone is not sufficient to identify the context). This covers template
7083 /// instantiation and various forms of implicitly-generated functions.
7084 struct CodeSynthesisContext {
7085 /// \brief The kind of template instantiation we are performing
7086 enum SynthesisKind {
7087 /// We are instantiating a template declaration. The entity is
7088 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7089 TemplateInstantiation,
7090
7091 /// We are instantiating a default argument for a template
7092 /// parameter. The Entity is the template parameter whose argument is
7093 /// being instantiated, the Template is the template, and the
7094 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7095 /// specified.
7096 DefaultTemplateArgumentInstantiation,
7097
7098 /// We are instantiating a default argument for a function.
7099 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7100 /// provides the template arguments as specified.
7101 DefaultFunctionArgumentInstantiation,
7102
7103 /// We are substituting explicit template arguments provided for
7104 /// a function template. The entity is a FunctionTemplateDecl.
7105 ExplicitTemplateArgumentSubstitution,
7106
7107 /// We are substituting template argument determined as part of
7108 /// template argument deduction for either a class template
7109 /// partial specialization or a function template. The
7110 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7111 /// a TemplateDecl.
7112 DeducedTemplateArgumentSubstitution,
7113
7114 /// We are substituting prior template arguments into a new
7115 /// template parameter. The template parameter itself is either a
7116 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7117 PriorTemplateArgumentSubstitution,
7118
7119 /// We are checking the validity of a default template argument that
7120 /// has been used when naming a template-id.
7121 DefaultTemplateArgumentChecking,
7122
7123 /// We are instantiating the exception specification for a function
7124 /// template which was deferred until it was needed.
7125 ExceptionSpecInstantiation,
7126
7127 /// We are declaring an implicit special member function.
7128 DeclaringSpecialMember,
7129
7130 /// We are defining a synthesized function (such as a defaulted special
7131 /// member).
7132 DefiningSynthesizedFunction,
7133
7134 /// Added for Template instantiation observation.
7135 /// Memoization means we are _not_ instantiating a template because
7136 /// it is already instantiated (but we entered a context where we
7137 /// would have had to if it was not already instantiated).
7138 Memoization
7139 } Kind;
7140
7141 /// \brief Was the enclosing context a non-instantiation SFINAE context?
7142 bool SavedInNonInstantiationSFINAEContext;
7143
7144 /// \brief The point of instantiation or synthesis within the source code.
7145 SourceLocation PointOfInstantiation;
7146
7147 /// \brief The entity that is being synthesized.
7148 Decl *Entity;
7149
7150 /// \brief The template (or partial specialization) in which we are
7151 /// performing the instantiation, for substitutions of prior template
7152 /// arguments.
7153 NamedDecl *Template;
7154
7155 /// \brief The list of template arguments we are substituting, if they
7156 /// are not part of the entity.
7157 const TemplateArgument *TemplateArgs;
7158
7159 // FIXME: Wrap this union around more members, or perhaps store the
7160 // kind-specific members in the RAII object owning the context.
7161 union {
7162 /// \brief The number of template arguments in TemplateArgs.
7163 unsigned NumTemplateArgs;
7164
7165 /// \brief The special member being declared or defined.
7166 CXXSpecialMember SpecialMember;
7167 };
7168
7169 ArrayRef<TemplateArgument> template_arguments() const {
7170 assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void
(0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7170, __extension__ __PRETTY_FUNCTION__))
;
7171 return {TemplateArgs, NumTemplateArgs};
7172 }
7173
7174 /// \brief The template deduction info object associated with the
7175 /// substitution or checking of explicit or deduced template arguments.
7176 sema::TemplateDeductionInfo *DeductionInfo;
7177
7178 /// \brief The source range that covers the construct that cause
7179 /// the instantiation, e.g., the template-id that causes a class
7180 /// template instantiation.
7181 SourceRange InstantiationRange;
7182
7183 CodeSynthesisContext()
7184 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7185 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7186
7187 /// \brief Determines whether this template is an actual instantiation
7188 /// that should be counted toward the maximum instantiation depth.
7189 bool isInstantiationRecord() const;
7190 };
7191
7192 /// \brief List of active code synthesis contexts.
7193 ///
7194 /// This vector is treated as a stack. As synthesis of one entity requires
7195 /// synthesis of another, additional contexts are pushed onto the stack.
7196 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7197
7198 /// Specializations whose definitions are currently being instantiated.
7199 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7200
7201 /// Non-dependent types used in templates that have already been instantiated
7202 /// by some template instantiation.
7203 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7204
7205 /// \brief Extra modules inspected when performing a lookup during a template
7206 /// instantiation. Computed lazily.
7207 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7208
7209 /// \brief Cache of additional modules that should be used for name lookup
7210 /// within the current template instantiation. Computed lazily; use
7211 /// getLookupModules() to get a complete set.
7212 llvm::DenseSet<Module*> LookupModulesCache;
7213
7214 /// \brief Get the set of additional modules that should be checked during
7215 /// name lookup. A module and its imports become visible when instanting a
7216 /// template defined within it.
7217 llvm::DenseSet<Module*> &getLookupModules();
7218
7219 /// \brief Map from the most recent declaration of a namespace to the most
7220 /// recent visible declaration of that namespace.
7221 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7222
7223 /// \brief Whether we are in a SFINAE context that is not associated with
7224 /// template instantiation.
7225 ///
7226 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7227 /// of a template instantiation or template argument deduction.
7228 bool InNonInstantiationSFINAEContext;
7229
7230 /// \brief The number of \p CodeSynthesisContexts that are not template
7231 /// instantiations and, therefore, should not be counted as part of the
7232 /// instantiation depth.
7233 ///
7234 /// When the instantiation depth reaches the user-configurable limit
7235 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7236 // FIXME: Should we have a similar limit for other forms of synthesis?
7237 unsigned NonInstantiationEntries;
7238
7239 /// \brief The depth of the context stack at the point when the most recent
7240 /// error or warning was produced.
7241 ///
7242 /// This value is used to suppress printing of redundant context stacks
7243 /// when there are multiple errors or warnings in the same instantiation.
7244 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7245 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7246
7247 /// \brief The template instantiation callbacks to trace or track
7248 /// instantiations (objects can be chained).
7249 ///
7250 /// This callbacks is used to print, trace or track template
7251 /// instantiations as they are being constructed.
7252 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
7253 TemplateInstCallbacks;
7254
7255 /// \brief The current index into pack expansion arguments that will be
7256 /// used for substitution of parameter packs.
7257 ///
7258 /// The pack expansion index will be -1 to indicate that parameter packs
7259 /// should be instantiated as themselves. Otherwise, the index specifies
7260 /// which argument within the parameter pack will be used for substitution.
7261 int ArgumentPackSubstitutionIndex;
7262
7263 /// \brief RAII object used to change the argument pack substitution index
7264 /// within a \c Sema object.
7265 ///
7266 /// See \c ArgumentPackSubstitutionIndex for more information.
7267 class ArgumentPackSubstitutionIndexRAII {
7268 Sema &Self;
7269 int OldSubstitutionIndex;
7270
7271 public:
7272 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7273 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7274 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7275 }
7276
7277 ~ArgumentPackSubstitutionIndexRAII() {
7278 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7279 }
7280 };
7281
7282 friend class ArgumentPackSubstitutionRAII;
7283
7284 /// \brief For each declaration that involved template argument deduction, the
7285 /// set of diagnostics that were suppressed during that template argument
7286 /// deduction.
7287 ///
7288 /// FIXME: Serialize this structure to the AST file.
7289 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7290 SuppressedDiagnosticsMap;
7291 SuppressedDiagnosticsMap SuppressedDiagnostics;
7292
7293 /// \brief A stack object to be created when performing template
7294 /// instantiation.
7295 ///
7296 /// Construction of an object of type \c InstantiatingTemplate
7297 /// pushes the current instantiation onto the stack of active
7298 /// instantiations. If the size of this stack exceeds the maximum
7299 /// number of recursive template instantiations, construction
7300 /// produces an error and evaluates true.
7301 ///
7302 /// Destruction of this object will pop the named instantiation off
7303 /// the stack.
7304 struct InstantiatingTemplate {
7305 /// \brief Note that we are instantiating a class template,
7306 /// function template, variable template, alias template,
7307 /// or a member thereof.
7308 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7309 Decl *Entity,
7310 SourceRange InstantiationRange = SourceRange());
7311
7312 struct ExceptionSpecification {};
7313 /// \brief Note that we are instantiating an exception specification
7314 /// of a function template.
7315 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7316 FunctionDecl *Entity, ExceptionSpecification,
7317 SourceRange InstantiationRange = SourceRange());
7318
7319 /// \brief Note that we are instantiating a default argument in a
7320 /// template-id.
7321 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7322 TemplateParameter Param, TemplateDecl *Template,
7323 ArrayRef<TemplateArgument> TemplateArgs,
7324 SourceRange InstantiationRange = SourceRange());
7325
7326 /// \brief Note that we are substituting either explicitly-specified or
7327 /// deduced template arguments during function template argument deduction.
7328 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7329 FunctionTemplateDecl *FunctionTemplate,
7330 ArrayRef<TemplateArgument> TemplateArgs,
7331 CodeSynthesisContext::SynthesisKind Kind,
7332 sema::TemplateDeductionInfo &DeductionInfo,
7333 SourceRange InstantiationRange = SourceRange());
7334
7335 /// \brief Note that we are instantiating as part of template
7336 /// argument deduction for a class template declaration.
7337 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7338 TemplateDecl *Template,
7339 ArrayRef<TemplateArgument> TemplateArgs,
7340 sema::TemplateDeductionInfo &DeductionInfo,
7341 SourceRange InstantiationRange = SourceRange());
7342
7343 /// \brief Note that we are instantiating as part of template
7344 /// argument deduction for a class template partial
7345 /// specialization.
7346 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7347 ClassTemplatePartialSpecializationDecl *PartialSpec,
7348 ArrayRef<TemplateArgument> TemplateArgs,
7349 sema::TemplateDeductionInfo &DeductionInfo,
7350 SourceRange InstantiationRange = SourceRange());
7351
7352 /// \brief Note that we are instantiating as part of template
7353 /// argument deduction for a variable template partial
7354 /// specialization.
7355 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7356 VarTemplatePartialSpecializationDecl *PartialSpec,
7357 ArrayRef<TemplateArgument> TemplateArgs,
7358 sema::TemplateDeductionInfo &DeductionInfo,
7359 SourceRange InstantiationRange = SourceRange());
7360
7361 /// \brief Note that we are instantiating a default argument for a function
7362 /// parameter.
7363 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7364 ParmVarDecl *Param,
7365 ArrayRef<TemplateArgument> TemplateArgs,
7366 SourceRange InstantiationRange = SourceRange());
7367
7368 /// \brief Note that we are substituting prior template arguments into a
7369 /// non-type parameter.
7370 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7371 NamedDecl *Template,
7372 NonTypeTemplateParmDecl *Param,
7373 ArrayRef<TemplateArgument> TemplateArgs,
7374 SourceRange InstantiationRange);
7375
7376 /// \brief Note that we are substituting prior template arguments into a
7377 /// template template parameter.
7378 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7379 NamedDecl *Template,
7380 TemplateTemplateParmDecl *Param,
7381 ArrayRef<TemplateArgument> TemplateArgs,
7382 SourceRange InstantiationRange);
7383
7384 /// \brief Note that we are checking the default template argument
7385 /// against the template parameter for a given template-id.
7386 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7387 TemplateDecl *Template,
7388 NamedDecl *Param,
7389 ArrayRef<TemplateArgument> TemplateArgs,
7390 SourceRange InstantiationRange);
7391
7392
7393 /// \brief Note that we have finished instantiating this template.
7394 void Clear();
7395
7396 ~InstantiatingTemplate() { Clear(); }
7397
7398 /// \brief Determines whether we have exceeded the maximum
7399 /// recursive template instantiations.
7400 bool isInvalid() const { return Invalid; }
7401
7402 /// \brief Determine whether we are already instantiating this
7403 /// specialization in some surrounding active instantiation.
7404 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7405
7406 private:
7407 Sema &SemaRef;
7408 bool Invalid;
7409 bool AlreadyInstantiating;
7410 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7411 SourceRange InstantiationRange);
7412
7413 InstantiatingTemplate(
7414 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7415 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7416 Decl *Entity, NamedDecl *Template = nullptr,
7417 ArrayRef<TemplateArgument> TemplateArgs = None,
7418 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7419
7420 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7421
7422 InstantiatingTemplate&
7423 operator=(const InstantiatingTemplate&) = delete;
7424 };
7425
7426 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7427 void popCodeSynthesisContext();
7428
7429 /// Determine whether we are currently performing template instantiation.
7430 bool inTemplateInstantiation() const {
7431 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7432 }
7433
7434 void PrintContextStack() {
7435 if (!CodeSynthesisContexts.empty() &&
7436 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7437 PrintInstantiationStack();
7438 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7439 }
7440 if (PragmaAttributeCurrentTargetDecl)
7441 PrintPragmaAttributeInstantiationPoint();
7442 }
7443 void PrintInstantiationStack();
7444
7445 void PrintPragmaAttributeInstantiationPoint();
7446
7447 /// \brief Determines whether we are currently in a context where
7448 /// template argument substitution failures are not considered
7449 /// errors.
7450 ///
7451 /// \returns An empty \c Optional if we're not in a SFINAE context.
7452 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7453 /// template-deduction context object, which can be used to capture
7454 /// diagnostics that will be suppressed.
7455 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7456
7457 /// \brief Determines whether we are currently in a context that
7458 /// is not evaluated as per C++ [expr] p5.
7459 bool isUnevaluatedContext() const {
7460 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7461, __extension__ __PRETTY_FUNCTION__))
7461 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7461, __extension__ __PRETTY_FUNCTION__))
;
7462 return ExprEvalContexts.back().isUnevaluated();
7463 }
7464
7465 /// \brief RAII class used to determine whether SFINAE has
7466 /// trapped any errors that occur during template argument
7467 /// deduction.
7468 class SFINAETrap {
7469 Sema &SemaRef;
7470 unsigned PrevSFINAEErrors;
7471 bool PrevInNonInstantiationSFINAEContext;
7472 bool PrevAccessCheckingSFINAE;
7473 bool PrevLastDiagnosticIgnored;
7474
7475 public:
7476 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7477 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7478 PrevInNonInstantiationSFINAEContext(
7479 SemaRef.InNonInstantiationSFINAEContext),
7480 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
7481 PrevLastDiagnosticIgnored(
7482 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
7483 {
7484 if (!SemaRef.isSFINAEContext())
7485 SemaRef.InNonInstantiationSFINAEContext = true;
7486 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7487 }
7488
7489 ~SFINAETrap() {
7490 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7491 SemaRef.InNonInstantiationSFINAEContext
7492 = PrevInNonInstantiationSFINAEContext;
7493 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7494 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
7495 PrevLastDiagnosticIgnored);
7496 }
7497
7498 /// \brief Determine whether any SFINAE errors have been trapped.
7499 bool hasErrorOccurred() const {
7500 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7501 }
7502 };
7503
7504 /// \brief RAII class used to indicate that we are performing provisional
7505 /// semantic analysis to determine the validity of a construct, so
7506 /// typo-correction and diagnostics in the immediate context (not within
7507 /// implicitly-instantiated templates) should be suppressed.
7508 class TentativeAnalysisScope {
7509 Sema &SemaRef;
7510 // FIXME: Using a SFINAETrap for this is a hack.
7511 SFINAETrap Trap;
7512 bool PrevDisableTypoCorrection;
7513 public:
7514 explicit TentativeAnalysisScope(Sema &SemaRef)
7515 : SemaRef(SemaRef), Trap(SemaRef, true),
7516 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7517 SemaRef.DisableTypoCorrection = true;
7518 }
7519 ~TentativeAnalysisScope() {
7520 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7521 }
7522 };
7523
7524 /// \brief The current instantiation scope used to store local
7525 /// variables.
7526 LocalInstantiationScope *CurrentInstantiationScope;
7527
7528 /// \brief Tracks whether we are in a context where typo correction is
7529 /// disabled.
7530 bool DisableTypoCorrection;
7531
7532 /// \brief The number of typos corrected by CorrectTypo.
7533 unsigned TyposCorrected;
7534
7535 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7536 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7537
7538 /// \brief A cache containing identifiers for which typo correction failed and
7539 /// their locations, so that repeated attempts to correct an identifier in a
7540 /// given location are ignored if typo correction already failed for it.
7541 IdentifierSourceLocations TypoCorrectionFailures;
7542
7543 /// \brief Worker object for performing CFG-based warnings.
7544 sema::AnalysisBasedWarnings AnalysisWarnings;
7545 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7546
7547 /// \brief An entity for which implicit template instantiation is required.
7548 ///
7549 /// The source location associated with the declaration is the first place in
7550 /// the source code where the declaration was "used". It is not necessarily
7551 /// the point of instantiation (which will be either before or after the
7552 /// namespace-scope declaration that triggered this implicit instantiation),
7553 /// However, it is the location that diagnostics should generally refer to,
7554 /// because users will need to know what code triggered the instantiation.
7555 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7556
7557 /// \brief The queue of implicit template instantiations that are required
7558 /// but have not yet been performed.
7559 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7560
7561 class GlobalEagerInstantiationScope {
7562 public:
7563 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7564 : S(S), Enabled(Enabled) {
7565 if (!Enabled) return;
7566
7567 SavedPendingInstantiations.swap(S.PendingInstantiations);
7568 SavedVTableUses.swap(S.VTableUses);
7569 }
7570
7571 void perform() {
7572 if (Enabled) {
7573 S.DefineUsedVTables();
7574 S.PerformPendingInstantiations();
7575 }
7576 }
7577
7578 ~GlobalEagerInstantiationScope() {
7579 if (!Enabled) return;
7580
7581 // Restore the set of pending vtables.
7582 assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7583, __extension__ __PRETTY_FUNCTION__))
7583 "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7583, __extension__ __PRETTY_FUNCTION__))
;
7584 S.VTableUses.swap(SavedVTableUses);
7585
7586 // Restore the set of pending implicit instantiations.
7587 assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7588, __extension__ __PRETTY_FUNCTION__))
7588 "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7588, __extension__ __PRETTY_FUNCTION__))
;
7589 S.PendingInstantiations.swap(SavedPendingInstantiations);
7590 }
7591
7592 private:
7593 Sema &S;
7594 SmallVector<VTableUse, 16> SavedVTableUses;
7595 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7596 bool Enabled;
7597 };
7598
7599 /// \brief The queue of implicit template instantiations that are required
7600 /// and must be performed within the current local scope.
7601 ///
7602 /// This queue is only used for member functions of local classes in
7603 /// templates, which must be instantiated in the same scope as their
7604 /// enclosing function, so that they can reference function-local
7605 /// types, static variables, enumerators, etc.
7606 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7607
7608 class LocalEagerInstantiationScope {
7609 public:
7610 LocalEagerInstantiationScope(Sema &S) : S(S) {
7611 SavedPendingLocalImplicitInstantiations.swap(
7612 S.PendingLocalImplicitInstantiations);
7613 }
7614
7615 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7616
7617 ~LocalEagerInstantiationScope() {
7618 assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7619, __extension__ __PRETTY_FUNCTION__))
7619 "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7619, __extension__ __PRETTY_FUNCTION__))
;
7620 SavedPendingLocalImplicitInstantiations.swap(
7621 S.PendingLocalImplicitInstantiations);
7622 }
7623
7624 private:
7625 Sema &S;
7626 std::deque<PendingImplicitInstantiation>
7627 SavedPendingLocalImplicitInstantiations;
7628 };
7629
7630 /// A helper class for building up ExtParameterInfos.
7631 class ExtParameterInfoBuilder {
7632 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7633 bool HasInteresting = false;
7634
7635 public:
7636 /// Set the ExtParameterInfo for the parameter at the given index,
7637 ///
7638 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7639 assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void (
0) : __assert_fail ("Infos.size() <= index", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 7639, __extension__ __PRETTY_FUNCTION__))
;
7640 Infos.resize(index);
7641 Infos.push_back(info);
7642
7643 if (!HasInteresting)
7644 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7645 }
7646
7647 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7648 /// ExtParameterInfo array we've built up.
7649 const FunctionProtoType::ExtParameterInfo *
7650 getPointerOrNull(unsigned numParams) {
7651 if (!HasInteresting) return nullptr;
7652 Infos.resize(numParams);
7653 return Infos.data();
7654 }
7655 };
7656
7657 void PerformPendingInstantiations(bool LocalOnly = false);
7658
7659 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7660 const MultiLevelTemplateArgumentList &TemplateArgs,
7661 SourceLocation Loc, DeclarationName Entity,
7662 bool AllowDeducedTST = false);
7663
7664 QualType SubstType(QualType T,
7665 const MultiLevelTemplateArgumentList &TemplateArgs,
7666 SourceLocation Loc, DeclarationName Entity);
7667
7668 TypeSourceInfo *SubstType(TypeLoc TL,
7669 const MultiLevelTemplateArgumentList &TemplateArgs,
7670 SourceLocation Loc, DeclarationName Entity);
7671
7672 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7673 const MultiLevelTemplateArgumentList &TemplateArgs,
7674 SourceLocation Loc,
7675 DeclarationName Entity,
7676 CXXRecordDecl *ThisContext,
7677 unsigned ThisTypeQuals);
7678 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7679 const MultiLevelTemplateArgumentList &Args);
7680 bool SubstExceptionSpec(SourceLocation Loc,
7681 FunctionProtoType::ExceptionSpecInfo &ESI,
7682 SmallVectorImpl<QualType> &ExceptionStorage,
7683 const MultiLevelTemplateArgumentList &Args);
7684 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7685 const MultiLevelTemplateArgumentList &TemplateArgs,
7686 int indexAdjustment,
7687 Optional<unsigned> NumExpansions,
7688 bool ExpectParameterPack);
7689 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7690 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7691 const MultiLevelTemplateArgumentList &TemplateArgs,
7692 SmallVectorImpl<QualType> &ParamTypes,
7693 SmallVectorImpl<ParmVarDecl *> *OutParams,
7694 ExtParameterInfoBuilder &ParamInfos);
7695 ExprResult SubstExpr(Expr *E,
7696 const MultiLevelTemplateArgumentList &TemplateArgs);
7697
7698 /// \brief Substitute the given template arguments into a list of
7699 /// expressions, expanding pack expansions if required.
7700 ///
7701 /// \param Exprs The list of expressions to substitute into.
7702 ///
7703 /// \param IsCall Whether this is some form of call, in which case
7704 /// default arguments will be dropped.
7705 ///
7706 /// \param TemplateArgs The set of template arguments to substitute.
7707 ///
7708 /// \param Outputs Will receive all of the substituted arguments.
7709 ///
7710 /// \returns true if an error occurred, false otherwise.
7711 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7712 const MultiLevelTemplateArgumentList &TemplateArgs,
7713 SmallVectorImpl<Expr *> &Outputs);
7714
7715 StmtResult SubstStmt(Stmt *S,
7716 const MultiLevelTemplateArgumentList &TemplateArgs);
7717
7718 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7719 const MultiLevelTemplateArgumentList &TemplateArgs);
7720
7721 ExprResult SubstInitializer(Expr *E,
7722 const MultiLevelTemplateArgumentList &TemplateArgs,
7723 bool CXXDirectInit);
7724
7725 bool
7726 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7727 CXXRecordDecl *Pattern,
7728 const MultiLevelTemplateArgumentList &TemplateArgs);
7729
7730 bool
7731 InstantiateClass(SourceLocation PointOfInstantiation,
7732 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7733 const MultiLevelTemplateArgumentList &TemplateArgs,
7734 TemplateSpecializationKind TSK,
7735 bool Complain = true);
7736
7737 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7738 EnumDecl *Instantiation, EnumDecl *Pattern,
7739 const MultiLevelTemplateArgumentList &TemplateArgs,
7740 TemplateSpecializationKind TSK);
7741
7742 bool InstantiateInClassInitializer(
7743 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7744 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7745
7746 struct LateInstantiatedAttribute {
7747 const Attr *TmplAttr;
7748 LocalInstantiationScope *Scope;
7749 Decl *NewDecl;
7750
7751 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7752 Decl *D)
7753 : TmplAttr(A), Scope(S), NewDecl(D)
7754 { }
7755 };
7756 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7757
7758 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7759 const Decl *Pattern, Decl *Inst,
7760 LateInstantiatedAttrVec *LateAttrs = nullptr,
7761 LocalInstantiationScope *OuterMostScope = nullptr);
7762
7763 void
7764 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7765 const Decl *Pattern, Decl *Inst,
7766 LateInstantiatedAttrVec *LateAttrs = nullptr,
7767 LocalInstantiationScope *OuterMostScope = nullptr);
7768
7769 bool usesPartialOrExplicitSpecialization(
7770 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7771
7772 bool
7773 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7774 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7775 TemplateSpecializationKind TSK,
7776 bool Complain = true);
7777
7778 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7779 CXXRecordDecl *Instantiation,
7780 const MultiLevelTemplateArgumentList &TemplateArgs,
7781 TemplateSpecializationKind TSK);
7782
7783 void InstantiateClassTemplateSpecializationMembers(
7784 SourceLocation PointOfInstantiation,
7785 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7786 TemplateSpecializationKind TSK);
7787
7788 NestedNameSpecifierLoc
7789 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7790 const MultiLevelTemplateArgumentList &TemplateArgs);
7791
7792 DeclarationNameInfo
7793 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7794 const MultiLevelTemplateArgumentList &TemplateArgs);
7795 TemplateName
7796 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7797 SourceLocation Loc,
7798 const MultiLevelTemplateArgumentList &TemplateArgs);
7799 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7800 TemplateArgumentListInfo &Result,
7801 const MultiLevelTemplateArgumentList &TemplateArgs);
7802
7803 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7804 FunctionDecl *Function);
7805 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
7806 const TemplateArgumentList *Args,
7807 SourceLocation Loc);
7808 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7809 FunctionDecl *Function,
7810 bool Recursive = false,
7811 bool DefinitionRequired = false,
7812 bool AtEndOfTU = false);
7813 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7814 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7815 const TemplateArgumentList &TemplateArgList,
7816 const TemplateArgumentListInfo &TemplateArgsInfo,
7817 SmallVectorImpl<TemplateArgument> &Converted,
7818 SourceLocation PointOfInstantiation, void *InsertPos,
7819 LateInstantiatedAttrVec *LateAttrs = nullptr,
7820 LocalInstantiationScope *StartingScope = nullptr);
7821 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7822 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7823 const MultiLevelTemplateArgumentList &TemplateArgs);
7824 void
7825 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7826 const MultiLevelTemplateArgumentList &TemplateArgs,
7827 LateInstantiatedAttrVec *LateAttrs,
7828 DeclContext *Owner,
7829 LocalInstantiationScope *StartingScope,
7830 bool InstantiatingVarTemplate = false);
7831 void InstantiateVariableInitializer(
7832 VarDecl *Var, VarDecl *OldVar,
7833 const MultiLevelTemplateArgumentList &TemplateArgs);
7834 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7835 VarDecl *Var, bool Recursive = false,
7836 bool DefinitionRequired = false,
7837 bool AtEndOfTU = false);
7838
7839 void InstantiateMemInitializers(CXXConstructorDecl *New,
7840 const CXXConstructorDecl *Tmpl,
7841 const MultiLevelTemplateArgumentList &TemplateArgs);
7842
7843 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7844 const MultiLevelTemplateArgumentList &TemplateArgs,
7845 bool FindingInstantiatedContext = false);
7846 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7847 const MultiLevelTemplateArgumentList &TemplateArgs);
7848
7849 // Objective-C declarations.
7850 enum ObjCContainerKind {
7851 OCK_None = -1,
7852 OCK_Interface = 0,
7853 OCK_Protocol,
7854 OCK_Category,
7855 OCK_ClassExtension,
7856 OCK_Implementation,
7857 OCK_CategoryImplementation
7858 };
7859 ObjCContainerKind getObjCContainerKind() const;
7860
7861 DeclResult actOnObjCTypeParam(Scope *S,
7862 ObjCTypeParamVariance variance,
7863 SourceLocation varianceLoc,
7864 unsigned index,
7865 IdentifierInfo *paramName,
7866 SourceLocation paramLoc,
7867 SourceLocation colonLoc,
7868 ParsedType typeBound);
7869
7870 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7871 ArrayRef<Decl *> typeParams,
7872 SourceLocation rAngleLoc);
7873 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7874
7875 Decl *ActOnStartClassInterface(Scope *S,
7876 SourceLocation AtInterfaceLoc,
7877 IdentifierInfo *ClassName,
7878 SourceLocation ClassLoc,
7879 ObjCTypeParamList *typeParamList,
7880 IdentifierInfo *SuperName,
7881 SourceLocation SuperLoc,
7882 ArrayRef<ParsedType> SuperTypeArgs,
7883 SourceRange SuperTypeArgsRange,
7884 Decl * const *ProtoRefs,
7885 unsigned NumProtoRefs,
7886 const SourceLocation *ProtoLocs,
7887 SourceLocation EndProtoLoc,
7888 AttributeList *AttrList);
7889
7890 void ActOnSuperClassOfClassInterface(Scope *S,
7891 SourceLocation AtInterfaceLoc,
7892 ObjCInterfaceDecl *IDecl,
7893 IdentifierInfo *ClassName,
7894 SourceLocation ClassLoc,
7895 IdentifierInfo *SuperName,
7896 SourceLocation SuperLoc,
7897 ArrayRef<ParsedType> SuperTypeArgs,
7898 SourceRange SuperTypeArgsRange);
7899
7900 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7901 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7902 IdentifierInfo *SuperName,
7903 SourceLocation SuperLoc);
7904
7905 Decl *ActOnCompatibilityAlias(
7906 SourceLocation AtCompatibilityAliasLoc,
7907 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7908 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7909
7910 bool CheckForwardProtocolDeclarationForCircularDependency(
7911 IdentifierInfo *PName,
7912 SourceLocation &PLoc, SourceLocation PrevLoc,
7913 const ObjCList<ObjCProtocolDecl> &PList);
7914
7915 Decl *ActOnStartProtocolInterface(
7916 SourceLocation AtProtoInterfaceLoc,
7917 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7918 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7919 const SourceLocation *ProtoLocs,
7920 SourceLocation EndProtoLoc,
7921 AttributeList *AttrList);
7922
7923 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7924 IdentifierInfo *ClassName,
7925 SourceLocation ClassLoc,
7926 ObjCTypeParamList *typeParamList,
7927 IdentifierInfo *CategoryName,
7928 SourceLocation CategoryLoc,
7929 Decl * const *ProtoRefs,
7930 unsigned NumProtoRefs,
7931 const SourceLocation *ProtoLocs,
7932 SourceLocation EndProtoLoc,
7933 AttributeList *AttrList);
7934
7935 Decl *ActOnStartClassImplementation(
7936 SourceLocation AtClassImplLoc,
7937 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7938 IdentifierInfo *SuperClassname,
7939 SourceLocation SuperClassLoc);
7940
7941 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7942 IdentifierInfo *ClassName,
7943 SourceLocation ClassLoc,
7944 IdentifierInfo *CatName,
7945 SourceLocation CatLoc);
7946
7947 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7948 ArrayRef<Decl *> Decls);
7949
7950 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7951 IdentifierInfo **IdentList,
7952 SourceLocation *IdentLocs,
7953 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7954 unsigned NumElts);
7955
7956 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7957 ArrayRef<IdentifierLocPair> IdentList,
7958 AttributeList *attrList);
7959
7960 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7961 ArrayRef<IdentifierLocPair> ProtocolId,
7962 SmallVectorImpl<Decl *> &Protocols);
7963
7964 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7965 SourceLocation ProtocolLoc,
7966 IdentifierInfo *TypeArgId,
7967 SourceLocation TypeArgLoc,
7968 bool SelectProtocolFirst = false);
7969
7970 /// Given a list of identifiers (and their locations), resolve the
7971 /// names to either Objective-C protocol qualifiers or type
7972 /// arguments, as appropriate.
7973 void actOnObjCTypeArgsOrProtocolQualifiers(
7974 Scope *S,
7975 ParsedType baseType,
7976 SourceLocation lAngleLoc,
7977 ArrayRef<IdentifierInfo *> identifiers,
7978 ArrayRef<SourceLocation> identifierLocs,
7979 SourceLocation rAngleLoc,
7980 SourceLocation &typeArgsLAngleLoc,
7981 SmallVectorImpl<ParsedType> &typeArgs,
7982 SourceLocation &typeArgsRAngleLoc,
7983 SourceLocation &protocolLAngleLoc,
7984 SmallVectorImpl<Decl *> &protocols,
7985 SourceLocation &protocolRAngleLoc,
7986 bool warnOnIncompleteProtocols);
7987
7988 /// Build a an Objective-C protocol-qualified 'id' type where no
7989 /// base type was specified.
7990 TypeResult actOnObjCProtocolQualifierType(
7991 SourceLocation lAngleLoc,
7992 ArrayRef<Decl *> protocols,
7993 ArrayRef<SourceLocation> protocolLocs,
7994 SourceLocation rAngleLoc);
7995
7996 /// Build a specialized and/or protocol-qualified Objective-C type.
7997 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7998 Scope *S,
7999 SourceLocation Loc,
8000 ParsedType BaseType,
8001 SourceLocation TypeArgsLAngleLoc,
8002 ArrayRef<ParsedType> TypeArgs,
8003 SourceLocation TypeArgsRAngleLoc,
8004 SourceLocation ProtocolLAngleLoc,
8005 ArrayRef<Decl *> Protocols,
8006 ArrayRef<SourceLocation> ProtocolLocs,
8007 SourceLocation ProtocolRAngleLoc);
8008
8009 /// Build an Objective-C type parameter type.
8010 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8011 SourceLocation ProtocolLAngleLoc,
8012 ArrayRef<ObjCProtocolDecl *> Protocols,
8013 ArrayRef<SourceLocation> ProtocolLocs,
8014 SourceLocation ProtocolRAngleLoc,
8015 bool FailOnError = false);
8016
8017 /// Build an Objective-C object pointer type.
8018 QualType BuildObjCObjectType(QualType BaseType,
8019 SourceLocation Loc,
8020 SourceLocation TypeArgsLAngleLoc,
8021 ArrayRef<TypeSourceInfo *> TypeArgs,
8022 SourceLocation TypeArgsRAngleLoc,
8023 SourceLocation ProtocolLAngleLoc,
8024 ArrayRef<ObjCProtocolDecl *> Protocols,
8025 ArrayRef<SourceLocation> ProtocolLocs,
8026 SourceLocation ProtocolRAngleLoc,
8027 bool FailOnError = false);
8028
8029 /// Check the application of the Objective-C '__kindof' qualifier to
8030 /// the given type.
8031 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
8032
8033 /// Ensure attributes are consistent with type.
8034 /// \param [in, out] Attributes The attributes to check; they will
8035 /// be modified to be consistent with \p PropertyTy.
8036 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8037 SourceLocation Loc,
8038 unsigned &Attributes,
8039 bool propertyInPrimaryClass);
8040
8041 /// Process the specified property declaration and create decls for the
8042 /// setters and getters as needed.
8043 /// \param property The property declaration being processed
8044 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8045
8046
8047 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8048 ObjCPropertyDecl *SuperProperty,
8049 const IdentifierInfo *Name,
8050 bool OverridingProtocolProperty);
8051
8052 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8053 ObjCInterfaceDecl *ID);
8054
8055 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8056 ArrayRef<Decl *> allMethods = None,
8057 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8058
8059 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8060 SourceLocation LParenLoc,
8061 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8062 Selector GetterSel, Selector SetterSel,
8063 tok::ObjCKeywordKind MethodImplKind,
8064 DeclContext *lexicalDC = nullptr);
8065
8066 Decl *ActOnPropertyImplDecl(Scope *S,
8067 SourceLocation AtLoc,
8068 SourceLocation PropertyLoc,
8069 bool ImplKind,
8070 IdentifierInfo *PropertyId,
8071 IdentifierInfo *PropertyIvar,
8072 SourceLocation PropertyIvarLoc,
8073 ObjCPropertyQueryKind QueryKind);
8074
8075 enum ObjCSpecialMethodKind {
8076 OSMK_None,
8077 OSMK_Alloc,
8078 OSMK_New,
8079 OSMK_Copy,
8080 OSMK_RetainingInit,
8081 OSMK_NonRetainingInit
8082 };
8083
8084 struct ObjCArgInfo {
8085 IdentifierInfo *Name;
8086 SourceLocation NameLoc;
8087 // The Type is null if no type was specified, and the DeclSpec is invalid
8088 // in this case.
8089 ParsedType Type;
8090 ObjCDeclSpec DeclSpec;
8091
8092 /// ArgAttrs - Attribute list for this argument.
8093 AttributeList *ArgAttrs;
8094 };
8095
8096 Decl *ActOnMethodDeclaration(
8097 Scope *S,
8098 SourceLocation BeginLoc, // location of the + or -.
8099 SourceLocation EndLoc, // location of the ; or {.
8100 tok::TokenKind MethodType,
8101 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8102 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8103 // optional arguments. The number of types/arguments is obtained
8104 // from the Sel.getNumArgs().
8105 ObjCArgInfo *ArgInfo,
8106 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
8107 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
8108 bool isVariadic, bool MethodDefinition);
8109
8110 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8111 const ObjCObjectPointerType *OPT,
8112 bool IsInstance);
8113 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8114 bool IsInstance);
8115
8116 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8117 bool inferObjCARCLifetime(ValueDecl *decl);
8118
8119 ExprResult
8120 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8121 Expr *BaseExpr,
8122 SourceLocation OpLoc,
8123 DeclarationName MemberName,
8124 SourceLocation MemberLoc,
8125 SourceLocation SuperLoc, QualType SuperType,
8126 bool Super);
8127
8128 ExprResult
8129 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8130 IdentifierInfo &propertyName,
8131 SourceLocation receiverNameLoc,
8132 SourceLocation propertyNameLoc);
8133
8134 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8135
8136 /// \brief Describes the kind of message expression indicated by a message
8137 /// send that starts with an identifier.
8138 enum ObjCMessageKind {
8139 /// \brief The message is sent to 'super'.
8140 ObjCSuperMessage,
8141 /// \brief The message is an instance message.
8142 ObjCInstanceMessage,
8143 /// \brief The message is a class message, and the identifier is a type
8144 /// name.
8145 ObjCClassMessage
8146 };
8147
8148 ObjCMessageKind getObjCMessageKind(Scope *S,
8149 IdentifierInfo *Name,
8150 SourceLocation NameLoc,
8151 bool IsSuper,
8152 bool HasTrailingDot,
8153 ParsedType &ReceiverType);
8154
8155 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8156 Selector Sel,
8157 SourceLocation LBracLoc,
8158 ArrayRef<SourceLocation> SelectorLocs,
8159 SourceLocation RBracLoc,
8160 MultiExprArg Args);
8161
8162 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8163 QualType ReceiverType,
8164 SourceLocation SuperLoc,
8165 Selector Sel,
8166 ObjCMethodDecl *Method,
8167 SourceLocation LBracLoc,
8168 ArrayRef<SourceLocation> SelectorLocs,
8169 SourceLocation RBracLoc,
8170 MultiExprArg Args,
8171 bool isImplicit = false);
8172
8173 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8174 bool isSuperReceiver,
8175 SourceLocation Loc,
8176 Selector Sel,
8177 ObjCMethodDecl *Method,
8178 MultiExprArg Args);
8179
8180 ExprResult ActOnClassMessage(Scope *S,
8181 ParsedType Receiver,
8182 Selector Sel,
8183 SourceLocation LBracLoc,
8184 ArrayRef<SourceLocation> SelectorLocs,
8185 SourceLocation RBracLoc,
8186 MultiExprArg Args);
8187
8188 ExprResult BuildInstanceMessage(Expr *Receiver,
8189 QualType ReceiverType,
8190 SourceLocation SuperLoc,
8191 Selector Sel,
8192 ObjCMethodDecl *Method,
8193 SourceLocation LBracLoc,
8194 ArrayRef<SourceLocation> SelectorLocs,
8195 SourceLocation RBracLoc,
8196 MultiExprArg Args,
8197 bool isImplicit = false);
8198
8199 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8200 QualType ReceiverType,
8201 SourceLocation Loc,
8202 Selector Sel,
8203 ObjCMethodDecl *Method,
8204 MultiExprArg Args);
8205
8206 ExprResult ActOnInstanceMessage(Scope *S,
8207 Expr *Receiver,
8208 Selector Sel,
8209 SourceLocation LBracLoc,
8210 ArrayRef<SourceLocation> SelectorLocs,
8211 SourceLocation RBracLoc,
8212 MultiExprArg Args);
8213
8214 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8215 ObjCBridgeCastKind Kind,
8216 SourceLocation BridgeKeywordLoc,
8217 TypeSourceInfo *TSInfo,
8218 Expr *SubExpr);
8219
8220 ExprResult ActOnObjCBridgedCast(Scope *S,
8221 SourceLocation LParenLoc,
8222 ObjCBridgeCastKind Kind,
8223 SourceLocation BridgeKeywordLoc,
8224 ParsedType Type,
8225 SourceLocation RParenLoc,
8226 Expr *SubExpr);
8227
8228 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8229
8230 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8231
8232 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8233 CastKind &Kind);
8234
8235 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8236 QualType DestType, QualType SrcType,
8237 ObjCInterfaceDecl *&RelatedClass,
8238 ObjCMethodDecl *&ClassMethod,
8239 ObjCMethodDecl *&InstanceMethod,
8240 TypedefNameDecl *&TDNDecl,
8241 bool CfToNs, bool Diagnose = true);
8242
8243 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8244 QualType DestType, QualType SrcType,
8245 Expr *&SrcExpr, bool Diagnose = true);
8246
8247 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8248 bool Diagnose = true);
8249
8250 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8251
8252 /// \brief Check whether the given new method is a valid override of the
8253 /// given overridden method, and set any properties that should be inherited.
8254 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8255 const ObjCMethodDecl *Overridden);
8256
8257 /// \brief Describes the compatibility of a result type with its method.
8258 enum ResultTypeCompatibilityKind {
8259 RTC_Compatible,
8260 RTC_Incompatible,
8261 RTC_Unknown
8262 };
8263
8264 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8265 ObjCInterfaceDecl *CurrentClass,
8266 ResultTypeCompatibilityKind RTC);
8267
8268 enum PragmaOptionsAlignKind {
8269 POAK_Native, // #pragma options align=native
8270 POAK_Natural, // #pragma options align=natural
8271 POAK_Packed, // #pragma options align=packed
8272 POAK_Power, // #pragma options align=power
8273 POAK_Mac68k, // #pragma options align=mac68k
8274 POAK_Reset // #pragma options align=reset
8275 };
8276
8277 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8278 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8279 PragmaClangSectionAction Action,
8280 PragmaClangSectionKind SecKind, StringRef SecName);
8281
8282 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8283 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8284 SourceLocation PragmaLoc);
8285
8286 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8287 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8288 StringRef SlotLabel, Expr *Alignment);
8289
8290 enum class PragmaPackDiagnoseKind {
8291 NonDefaultStateAtInclude,
8292 ChangedStateAtExit
8293 };
8294
8295 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
8296 SourceLocation IncludeLoc);
8297 void DiagnoseUnterminatedPragmaPack();
8298
8299 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8300 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8301
8302 /// ActOnPragmaMSComment - Called on well formed
8303 /// \#pragma comment(kind, "arg").
8304 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8305 StringRef Arg);
8306
8307 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8308 /// pointers_to_members(representation method[, general purpose
8309 /// representation]).
8310 void ActOnPragmaMSPointersToMembers(
8311 LangOptions::PragmaMSPointersToMembersKind Kind,
8312 SourceLocation PragmaLoc);
8313
8314 /// \brief Called on well formed \#pragma vtordisp().
8315 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8316 SourceLocation PragmaLoc,
8317 MSVtorDispAttr::Mode Value);
8318
8319 enum PragmaSectionKind {
8320 PSK_DataSeg,
8321 PSK_BSSSeg,
8322 PSK_ConstSeg,
8323 PSK_CodeSeg,
8324 };
8325
8326 bool UnifySection(StringRef SectionName,
8327 int SectionFlags,
8328 DeclaratorDecl *TheDecl);
8329 bool UnifySection(StringRef SectionName,
8330 int SectionFlags,
8331 SourceLocation PragmaSectionLocation);
8332
8333 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8334 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8335 PragmaMsStackAction Action,
8336 llvm::StringRef StackSlotLabel,
8337 StringLiteral *SegmentName,
8338 llvm::StringRef PragmaName);
8339
8340 /// \brief Called on well formed \#pragma section().
8341 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8342 int SectionFlags, StringLiteral *SegmentName);
8343
8344 /// \brief Called on well-formed \#pragma init_seg().
8345 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8346 StringLiteral *SegmentName);
8347
8348 /// \brief Called on #pragma clang __debug dump II
8349 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8350
8351 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8352 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8353 StringRef Value);
8354
8355 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8356 void ActOnPragmaUnused(const Token &Identifier,
8357 Scope *curScope,
8358 SourceLocation PragmaLoc);
8359
8360 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8361 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8362 SourceLocation PragmaLoc);
8363
8364 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8365 SourceLocation Loc);
8366 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8367
8368 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8369 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8370 SourceLocation PragmaLoc,
8371 SourceLocation WeakNameLoc);
8372
8373 /// ActOnPragmaRedefineExtname - Called on well formed
8374 /// \#pragma redefine_extname oldname newname.
8375 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8376 IdentifierInfo* AliasName,
8377 SourceLocation PragmaLoc,
8378 SourceLocation WeakNameLoc,
8379 SourceLocation AliasNameLoc);
8380
8381 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8382 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8383 IdentifierInfo* AliasName,
8384 SourceLocation PragmaLoc,
8385 SourceLocation WeakNameLoc,
8386 SourceLocation AliasNameLoc);
8387
8388 /// ActOnPragmaFPContract - Called on well formed
8389 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8390 /// \#pragma clang fp contract
8391 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8392
8393 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8394 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8395 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8396
8397 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8398 void AddMsStructLayoutForRecord(RecordDecl *RD);
8399
8400 /// FreePackedContext - Deallocate and null out PackContext.
8401 void FreePackedContext();
8402
8403 /// PushNamespaceVisibilityAttr - Note that we've entered a
8404 /// namespace with a visibility attribute.
8405 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8406 SourceLocation Loc);
8407
8408 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8409 /// add an appropriate visibility attribute.
8410 void AddPushedVisibilityAttribute(Decl *RD);
8411
8412 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8413 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8414 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8415
8416 /// FreeVisContext - Deallocate and null out VisContext.
8417 void FreeVisContext();
8418
8419 /// AddCFAuditedAttribute - Check whether we're currently within
8420 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8421 /// the appropriate attribute.
8422 void AddCFAuditedAttribute(Decl *D);
8423
8424 /// \brief Called on well-formed '\#pragma clang attribute push'.
8425 void ActOnPragmaAttributePush(AttributeList &Attribute,
8426 SourceLocation PragmaLoc,
8427 attr::ParsedSubjectMatchRuleSet Rules);
8428
8429 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8430 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8431
8432 /// \brief Adds the attributes that have been specified using the
8433 /// '\#pragma clang attribute push' directives to the given declaration.
8434 void AddPragmaAttributes(Scope *S, Decl *D);
8435
8436 void DiagnoseUnterminatedPragmaAttribute();
8437
8438 /// \brief Called on well formed \#pragma clang optimize.
8439 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8440
8441 /// \brief Get the location for the currently active "\#pragma clang optimize
8442 /// off". If this location is invalid, then the state of the pragma is "on".
8443 SourceLocation getOptimizeOffPragmaLocation() const {
8444 return OptimizeOffPragmaLocation;
8445 }
8446
8447 /// \brief Only called on function definitions; if there is a pragma in scope
8448 /// with the effect of a range-based optnone, consider marking the function
8449 /// with attribute optnone.
8450 void AddRangeBasedOptnone(FunctionDecl *FD);
8451
8452 /// \brief Adds the 'optnone' attribute to the function declaration if there
8453 /// are no conflicts; Loc represents the location causing the 'optnone'
8454 /// attribute to be added (usually because of a pragma).
8455 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8456
8457 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8458 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8459 unsigned SpellingListIndex, bool IsPackExpansion);
8460 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8461 unsigned SpellingListIndex, bool IsPackExpansion);
8462
8463 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8464 /// declaration.
8465 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8466 unsigned SpellingListIndex);
8467
8468 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8469 /// declaration.
8470 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8471 unsigned SpellingListIndex);
8472
8473 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8474 /// declaration.
8475 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8476 unsigned SpellingListIndex);
8477
8478 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8479 /// declaration.
8480 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8481 Expr *MinBlocks, unsigned SpellingListIndex);
8482
8483 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8484 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8485 unsigned SpellingListIndex, bool InInstantiation = false);
8486
8487 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8488 ParameterABI ABI, unsigned SpellingListIndex);
8489
8490 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8491 unsigned SpellingListIndex, bool isNSConsumed,
8492 bool isTemplateInstantiation);
8493
8494 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8495
8496 //===--------------------------------------------------------------------===//
8497 // C++ Coroutines TS
8498 //
8499 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8500 StringRef Keyword);
8501 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8502 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8503 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8504
8505 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8506 bool IsImplicit = false);
8507 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8508 UnresolvedLookupExpr* Lookup);
8509 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8510 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8511 bool IsImplicit = false);
8512 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8513 bool buildCoroutineParameterMoves(SourceLocation Loc);
8514 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8515 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8516
8517 //===--------------------------------------------------------------------===//
8518 // OpenCL extensions.
8519 //
8520private:
8521 std::string CurrOpenCLExtension;
8522 /// Extensions required by an OpenCL type.
8523 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8524 /// Extensions required by an OpenCL declaration.
8525 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8526public:
8527 llvm::StringRef getCurrentOpenCLExtension() const {
8528 return CurrOpenCLExtension;
8529 }
8530 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8531 CurrOpenCLExtension = Ext;
8532 }
8533
8534 /// \brief Set OpenCL extensions for a type which can only be used when these
8535 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8536 /// \param Exts A space separated list of OpenCL extensions.
8537 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8538
8539 /// \brief Set OpenCL extensions for a declaration which can only be
8540 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8541 /// nothing.
8542 /// \param Exts A space separated list of OpenCL extensions.
8543 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8544
8545 /// \brief Set current OpenCL extensions for a type which can only be used
8546 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8547 /// empty, do nothing.
8548 void setCurrentOpenCLExtensionForType(QualType T);
8549
8550 /// \brief Set current OpenCL extensions for a declaration which
8551 /// can only be used when these OpenCL extensions are enabled. If current
8552 /// OpenCL extension is empty, do nothing.
8553 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8554
8555 bool isOpenCLDisabledDecl(Decl *FD);
8556
8557 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8558 /// is disabled due to required OpenCL extensions being disabled. If so,
8559 /// emit diagnostics.
8560 /// \return true if type is disabled.
8561 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8562
8563 /// \brief Check if declaration \p D used by expression \p E
8564 /// is disabled due to required OpenCL extensions being disabled. If so,
8565 /// emit diagnostics.
8566 /// \return true if type is disabled.
8567 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8568
8569 //===--------------------------------------------------------------------===//
8570 // OpenMP directives and clauses.
8571 //
8572private:
8573 void *VarDataSharingAttributesStack;
8574 /// Set to true inside '#pragma omp declare target' region.
8575 bool IsInOpenMPDeclareTargetContext = false;
8576 /// \brief Initialization of data-sharing attributes stack.
8577 void InitDataSharingAttributesStack();
8578 void DestroyDataSharingAttributesStack();
8579 ExprResult
8580 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8581 bool StrictlyPositive = true);
8582 /// Returns OpenMP nesting level for current directive.
8583 unsigned getOpenMPNestingLevel() const;
8584
8585 /// Adjusts the function scopes index for the target-based regions.
8586 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
8587 unsigned Level) const;
8588
8589 /// Push new OpenMP function region for non-capturing function.
8590 void pushOpenMPFunctionRegion();
8591
8592 /// Pop OpenMP function region for non-capturing function.
8593 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8594
8595 /// Checks if a type or a declaration is disabled due to the owning extension
8596 /// being disabled, and emits diagnostic messages if it is disabled.
8597 /// \param D type or declaration to be checked.
8598 /// \param DiagLoc source location for the diagnostic message.
8599 /// \param DiagInfo information to be emitted for the diagnostic message.
8600 /// \param SrcRange source range of the declaration.
8601 /// \param Map maps type or declaration to the extensions.
8602 /// \param Selector selects diagnostic message: 0 for type and 1 for
8603 /// declaration.
8604 /// \return true if the type or declaration is disabled.
8605 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8606 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8607 MapT &Map, unsigned Selector = 0,
8608 SourceRange SrcRange = SourceRange());
8609
8610public:
8611 /// \brief Return true if the provided declaration \a VD should be captured by
8612 /// reference.
8613 /// \param Level Relative level of nested OpenMP construct for that the check
8614 /// is performed.
8615 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8616
8617 /// \brief Check if the specified variable is used in one of the private
8618 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8619 /// constructs.
8620 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8621 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8622 ExprObjectKind OK, SourceLocation Loc);
8623
8624 /// \brief Check if the specified variable is used in 'private' clause.
8625 /// \param Level Relative level of nested OpenMP construct for that the check
8626 /// is performed.
8627 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8628
8629 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
8630 /// for \p FD based on DSA for the provided corresponding captured declaration
8631 /// \p D.
8632 void setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level);
8633
8634 /// \brief Check if the specified variable is captured by 'target' directive.
8635 /// \param Level Relative level of nested OpenMP construct for that the check
8636 /// is performed.
8637 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8638
8639 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8640 Expr *Op);
8641 /// \brief Called on start of new data sharing attribute block.
8642 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8643 const DeclarationNameInfo &DirName, Scope *CurScope,
8644 SourceLocation Loc);
8645 /// \brief Start analysis of clauses.
8646 void StartOpenMPClause(OpenMPClauseKind K);
8647 /// \brief End analysis of clauses.
8648 void EndOpenMPClause();
8649 /// \brief Called on end of data sharing attribute block.
8650 void EndOpenMPDSABlock(Stmt *CurDirective);
8651
8652 /// \brief Check if the current region is an OpenMP loop region and if it is,
8653 /// mark loop control variable, used in \p Init for loop initialization, as
8654 /// private by default.
8655 /// \param Init First part of the for loop.
8656 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8657
8658 // OpenMP directives and clauses.
8659 /// \brief Called on correct id-expression from the '#pragma omp
8660 /// threadprivate'.
8661 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8662 CXXScopeSpec &ScopeSpec,
8663 const DeclarationNameInfo &Id);
8664 /// \brief Called on well-formed '#pragma omp threadprivate'.
8665 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8666 SourceLocation Loc,
8667 ArrayRef<Expr *> VarList);
8668 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8669 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8670 SourceLocation Loc,
8671 ArrayRef<Expr *> VarList);
8672 /// \brief Check if the specified type is allowed to be used in 'omp declare
8673 /// reduction' construct.
8674 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8675 TypeResult ParsedType);
8676 /// \brief Called on start of '#pragma omp declare reduction'.
8677 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8678 Scope *S, DeclContext *DC, DeclarationName Name,
8679 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8680 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8681 /// \brief Initialize declare reduction construct initializer.
8682 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8683 /// \brief Finish current declare reduction construct initializer.
8684 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8685 /// \brief Initialize declare reduction construct initializer.
8686 /// \return omp_priv variable.
8687 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8688 /// \brief Finish current declare reduction construct initializer.
8689 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
8690 VarDecl *OmpPrivParm);
8691 /// \brief Called at the end of '#pragma omp declare reduction'.
8692 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8693 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8694
8695 /// Called on the start of target region i.e. '#pragma omp declare target'.
8696 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8697 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8698 void ActOnFinishOpenMPDeclareTargetDirective();
8699 /// Called on correct id-expression from the '#pragma omp declare target'.
8700 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8701 const DeclarationNameInfo &Id,
8702 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8703 NamedDeclSetType &SameDirectiveDecls);
8704 /// Check declaration inside target region.
8705 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
8706 SourceLocation IdLoc = SourceLocation());
8707 /// Return true inside OpenMP declare target region.
8708 bool isInOpenMPDeclareTargetContext() const {
8709 return IsInOpenMPDeclareTargetContext;
8710 }
8711 /// Return true inside OpenMP target region.
8712 bool isInOpenMPTargetExecutionDirective() const;
8713 /// Return true if (un)supported features for the current target should be
8714 /// diagnosed if OpenMP (offloading) is enabled.
8715 bool shouldDiagnoseTargetSupportFromOpenMP() const {
8716 return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() ||
8717 isInOpenMPTargetExecutionDirective();
8718 }
8719
8720 /// Return the number of captured regions created for an OpenMP directive.
8721 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8722
8723 /// \brief Initialization of captured region for OpenMP region.
8724 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8725 /// \brief End of OpenMP region.
8726 ///
8727 /// \param S Statement associated with the current OpenMP region.
8728 /// \param Clauses List of clauses for the current OpenMP region.
8729 ///
8730 /// \returns Statement for finished OpenMP region.
8731 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8732 StmtResult ActOnOpenMPExecutableDirective(
8733 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8734 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8735 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8736 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8737 /// of the associated statement.
8738 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8739 Stmt *AStmt,
8740 SourceLocation StartLoc,
8741 SourceLocation EndLoc);
8742 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8743 /// of the associated statement.
8744 StmtResult ActOnOpenMPSimdDirective(
8745 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8746 SourceLocation EndLoc,
8747 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8748 /// \brief Called on well-formed '\#pragma omp for' after parsing
8749 /// of the associated statement.
8750 StmtResult ActOnOpenMPForDirective(
8751 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8752 SourceLocation EndLoc,
8753 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8754 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8755 /// of the associated statement.
8756 StmtResult ActOnOpenMPForSimdDirective(
8757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8758 SourceLocation EndLoc,
8759 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8760 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8761 /// of the associated statement.
8762 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8763 Stmt *AStmt, SourceLocation StartLoc,
8764 SourceLocation EndLoc);
8765 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8766 /// associated statement.
8767 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8768 SourceLocation EndLoc);
8769 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8770 /// associated statement.
8771 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8772 Stmt *AStmt, SourceLocation StartLoc,
8773 SourceLocation EndLoc);
8774 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8775 /// associated statement.
8776 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8777 SourceLocation EndLoc);
8778 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8779 /// associated statement.
8780 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8781 ArrayRef<OMPClause *> Clauses,
8782 Stmt *AStmt, SourceLocation StartLoc,
8783 SourceLocation EndLoc);
8784 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8785 /// of the associated statement.
8786 StmtResult ActOnOpenMPParallelForDirective(
8787 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8788 SourceLocation EndLoc,
8789 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8790 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8791 /// parsing of the associated statement.
8792 StmtResult ActOnOpenMPParallelForSimdDirective(
8793 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8794 SourceLocation EndLoc,
8795 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8796 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8797 /// parsing of the associated statement.
8798 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8799 Stmt *AStmt,
8800 SourceLocation StartLoc,
8801 SourceLocation EndLoc);
8802 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8803 /// associated statement.
8804 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8805 Stmt *AStmt, SourceLocation StartLoc,
8806 SourceLocation EndLoc);
8807 /// \brief Called on well-formed '\#pragma omp taskyield'.
8808 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8809 SourceLocation EndLoc);
8810 /// \brief Called on well-formed '\#pragma omp barrier'.
8811 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8812 SourceLocation EndLoc);
8813 /// \brief Called on well-formed '\#pragma omp taskwait'.
8814 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8815 SourceLocation EndLoc);
8816 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8817 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8818 Stmt *AStmt, SourceLocation StartLoc,
8819 SourceLocation EndLoc);
8820 /// \brief Called on well-formed '\#pragma omp flush'.
8821 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8822 SourceLocation StartLoc,
8823 SourceLocation EndLoc);
8824 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8825 /// associated statement.
8826 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8827 Stmt *AStmt, SourceLocation StartLoc,
8828 SourceLocation EndLoc);
8829 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8830 /// associated statement.
8831 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8832 Stmt *AStmt, SourceLocation StartLoc,
8833 SourceLocation EndLoc);
8834 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8835 /// associated statement.
8836 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8837 Stmt *AStmt, SourceLocation StartLoc,
8838 SourceLocation EndLoc);
8839 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8840 /// the associated statement.
8841 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8842 Stmt *AStmt, SourceLocation StartLoc,
8843 SourceLocation EndLoc);
8844 /// \brief Called on well-formed '\#pragma omp target enter data' after
8845 /// parsing of the associated statement.
8846 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8847 SourceLocation StartLoc,
8848 SourceLocation EndLoc,
8849 Stmt *AStmt);
8850 /// \brief Called on well-formed '\#pragma omp target exit data' after
8851 /// parsing of the associated statement.
8852 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8853 SourceLocation StartLoc,
8854 SourceLocation EndLoc,
8855 Stmt *AStmt);
8856 /// \brief Called on well-formed '\#pragma omp target parallel' after
8857 /// parsing of the associated statement.
8858 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8859 Stmt *AStmt,
8860 SourceLocation StartLoc,
8861 SourceLocation EndLoc);
8862 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8863 /// parsing of the associated statement.
8864 StmtResult ActOnOpenMPTargetParallelForDirective(
8865 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8866 SourceLocation EndLoc,
8867 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8868 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8869 /// associated statement.
8870 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8871 Stmt *AStmt, SourceLocation StartLoc,
8872 SourceLocation EndLoc);
8873 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8874 StmtResult
8875 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8876 SourceLocation EndLoc,
8877 OpenMPDirectiveKind CancelRegion);
8878 /// \brief Called on well-formed '\#pragma omp cancel'.
8879 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8880 SourceLocation StartLoc,
8881 SourceLocation EndLoc,
8882 OpenMPDirectiveKind CancelRegion);
8883 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8884 /// associated statement.
8885 StmtResult ActOnOpenMPTaskLoopDirective(
8886 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8887 SourceLocation EndLoc,
8888 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8889 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8890 /// the associated statement.
8891 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8892 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8893 SourceLocation EndLoc,
8894 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8895 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8896 /// of the associated statement.
8897 StmtResult ActOnOpenMPDistributeDirective(
8898 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8899 SourceLocation EndLoc,
8900 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8901 /// \brief Called on well-formed '\#pragma omp target update'.
8902 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8903 SourceLocation StartLoc,
8904 SourceLocation EndLoc,
8905 Stmt *AStmt);
8906 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8907 /// parsing of the associated statement.
8908 StmtResult ActOnOpenMPDistributeParallelForDirective(
8909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8910 SourceLocation EndLoc,
8911 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8912 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8913 /// after parsing of the associated statement.
8914 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8915 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8916 SourceLocation EndLoc,
8917 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8918 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8919 /// parsing of the associated statement.
8920 StmtResult ActOnOpenMPDistributeSimdDirective(
8921 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8922 SourceLocation EndLoc,
8923 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8924 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8925 /// parsing of the associated statement.
8926 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8927 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8928 SourceLocation EndLoc,
8929 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8930 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8931 /// the associated statement.
8932 StmtResult ActOnOpenMPTargetSimdDirective(
8933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8934 SourceLocation EndLoc,
8935 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8936 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8937 /// the associated statement.
8938 StmtResult ActOnOpenMPTeamsDistributeDirective(
8939 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8940 SourceLocation EndLoc,
8941 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8942 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8943 /// of the associated statement.
8944 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8945 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8946 SourceLocation EndLoc,
8947 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8948 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8949 /// after parsing of the associated statement.
8950 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8951 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8952 SourceLocation EndLoc,
8953 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8954 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8955 /// after parsing of the associated statement.
8956 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8957 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8958 SourceLocation EndLoc,
8959 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8960 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8961 /// associated statement.
8962 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8963 Stmt *AStmt,
8964 SourceLocation StartLoc,
8965 SourceLocation EndLoc);
8966 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8967 /// of the associated statement.
8968 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8969 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8970 SourceLocation EndLoc,
8971 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8972 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8973 /// after parsing of the associated statement.
8974 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8975 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8976 SourceLocation EndLoc,
8977 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8978 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8979 /// simd' after parsing of the associated statement.
8980 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8981 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8982 SourceLocation EndLoc,
8983 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8984 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8985 /// parsing of the associated statement.
8986 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8987 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8988 SourceLocation EndLoc,
8989 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8990
8991 /// Checks correctness of linear modifiers.
8992 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8993 SourceLocation LinLoc);
8994 /// Checks that the specified declaration matches requirements for the linear
8995 /// decls.
8996 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8997 OpenMPLinearClauseKind LinKind, QualType Type);
8998
8999 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
9000 /// the associated method/function.
9001 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
9002 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
9003 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
9004 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
9005 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
9006
9007 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
9008 Expr *Expr,
9009 SourceLocation StartLoc,
9010 SourceLocation LParenLoc,
9011 SourceLocation EndLoc);
9012 /// \brief Called on well-formed 'if' clause.
9013 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9014 Expr *Condition, SourceLocation StartLoc,
9015 SourceLocation LParenLoc,
9016 SourceLocation NameModifierLoc,
9017 SourceLocation ColonLoc,
9018 SourceLocation EndLoc);
9019 /// \brief Called on well-formed 'final' clause.
9020 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
9021 SourceLocation LParenLoc,
9022 SourceLocation EndLoc);
9023 /// \brief Called on well-formed 'num_threads' clause.
9024 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9025 SourceLocation StartLoc,
9026 SourceLocation LParenLoc,
9027 SourceLocation EndLoc);
9028 /// \brief Called on well-formed 'safelen' clause.
9029 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
9030 SourceLocation StartLoc,
9031 SourceLocation LParenLoc,
9032 SourceLocation EndLoc);
9033 /// \brief Called on well-formed 'simdlen' clause.
9034 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
9035 SourceLocation LParenLoc,
9036 SourceLocation EndLoc);
9037 /// \brief Called on well-formed 'collapse' clause.
9038 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
9039 SourceLocation StartLoc,
9040 SourceLocation LParenLoc,
9041 SourceLocation EndLoc);
9042 /// \brief Called on well-formed 'ordered' clause.
9043 OMPClause *
9044 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
9045 SourceLocation LParenLoc = SourceLocation(),
9046 Expr *NumForLoops = nullptr);
9047 /// \brief Called on well-formed 'grainsize' clause.
9048 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
9049 SourceLocation LParenLoc,
9050 SourceLocation EndLoc);
9051 /// \brief Called on well-formed 'num_tasks' clause.
9052 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
9053 SourceLocation LParenLoc,
9054 SourceLocation EndLoc);
9055 /// \brief Called on well-formed 'hint' clause.
9056 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
9057 SourceLocation LParenLoc,
9058 SourceLocation EndLoc);
9059
9060 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
9061 unsigned Argument,
9062 SourceLocation ArgumentLoc,
9063 SourceLocation StartLoc,
9064 SourceLocation LParenLoc,
9065 SourceLocation EndLoc);
9066 /// \brief Called on well-formed 'default' clause.
9067 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9068 SourceLocation KindLoc,
9069 SourceLocation StartLoc,
9070 SourceLocation LParenLoc,
9071 SourceLocation EndLoc);
9072 /// \brief Called on well-formed 'proc_bind' clause.
9073 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9074 SourceLocation KindLoc,
9075 SourceLocation StartLoc,
9076 SourceLocation LParenLoc,
9077 SourceLocation EndLoc);
9078
9079 OMPClause *ActOnOpenMPSingleExprWithArgClause(
9080 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
9081 SourceLocation StartLoc, SourceLocation LParenLoc,
9082 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
9083 SourceLocation EndLoc);
9084 /// \brief Called on well-formed 'schedule' clause.
9085 OMPClause *ActOnOpenMPScheduleClause(
9086 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9087 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9088 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9089 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
9090
9091 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
9092 SourceLocation EndLoc);
9093 /// \brief Called on well-formed 'nowait' clause.
9094 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9095 SourceLocation EndLoc);
9096 /// \brief Called on well-formed 'untied' clause.
9097 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9098 SourceLocation EndLoc);
9099 /// \brief Called on well-formed 'mergeable' clause.
9100 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9101 SourceLocation EndLoc);
9102 /// \brief Called on well-formed 'read' clause.
9103 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
9104 SourceLocation EndLoc);
9105 /// \brief Called on well-formed 'write' clause.
9106 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
9107 SourceLocation EndLoc);
9108 /// \brief Called on well-formed 'update' clause.
9109 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9110 SourceLocation EndLoc);
9111 /// \brief Called on well-formed 'capture' clause.
9112 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9113 SourceLocation EndLoc);
9114 /// \brief Called on well-formed 'seq_cst' clause.
9115 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9116 SourceLocation EndLoc);
9117 /// \brief Called on well-formed 'threads' clause.
9118 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9119 SourceLocation EndLoc);
9120 /// \brief Called on well-formed 'simd' clause.
9121 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9122 SourceLocation EndLoc);
9123 /// \brief Called on well-formed 'nogroup' clause.
9124 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9125 SourceLocation EndLoc);
9126
9127 OMPClause *ActOnOpenMPVarListClause(
9128 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
9129 SourceLocation StartLoc, SourceLocation LParenLoc,
9130 SourceLocation ColonLoc, SourceLocation EndLoc,
9131 CXXScopeSpec &ReductionIdScopeSpec,
9132 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9133 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9134 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9135 SourceLocation DepLinMapLoc);
9136 /// \brief Called on well-formed 'private' clause.
9137 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9138 SourceLocation StartLoc,
9139 SourceLocation LParenLoc,
9140 SourceLocation EndLoc);
9141 /// \brief Called on well-formed 'firstprivate' clause.
9142 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9143 SourceLocation StartLoc,
9144 SourceLocation LParenLoc,
9145 SourceLocation EndLoc);
9146 /// \brief Called on well-formed 'lastprivate' clause.
9147 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9148 SourceLocation StartLoc,
9149 SourceLocation LParenLoc,
9150 SourceLocation EndLoc);
9151 /// \brief Called on well-formed 'shared' clause.
9152 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9153 SourceLocation StartLoc,
9154 SourceLocation LParenLoc,
9155 SourceLocation EndLoc);
9156 /// \brief Called on well-formed 'reduction' clause.
9157 OMPClause *ActOnOpenMPReductionClause(
9158 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9159 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9160 CXXScopeSpec &ReductionIdScopeSpec,
9161 const DeclarationNameInfo &ReductionId,
9162 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9163 /// Called on well-formed 'task_reduction' clause.
9164 OMPClause *ActOnOpenMPTaskReductionClause(
9165 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9166 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9167 CXXScopeSpec &ReductionIdScopeSpec,
9168 const DeclarationNameInfo &ReductionId,
9169 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9170 /// Called on well-formed 'in_reduction' clause.
9171 OMPClause *ActOnOpenMPInReductionClause(
9172 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9173 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9174 CXXScopeSpec &ReductionIdScopeSpec,
9175 const DeclarationNameInfo &ReductionId,
9176 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9177 /// \brief Called on well-formed 'linear' clause.
9178 OMPClause *
9179 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9180 SourceLocation StartLoc, SourceLocation LParenLoc,
9181 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9182 SourceLocation ColonLoc, SourceLocation EndLoc);
9183 /// \brief Called on well-formed 'aligned' clause.
9184 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9185 Expr *Alignment,
9186 SourceLocation StartLoc,
9187 SourceLocation LParenLoc,
9188 SourceLocation ColonLoc,
9189 SourceLocation EndLoc);
9190 /// \brief Called on well-formed 'copyin' clause.
9191 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9192 SourceLocation StartLoc,
9193 SourceLocation LParenLoc,
9194 SourceLocation EndLoc);
9195 /// \brief Called on well-formed 'copyprivate' clause.
9196 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9197 SourceLocation StartLoc,
9198 SourceLocation LParenLoc,
9199 SourceLocation EndLoc);
9200 /// \brief Called on well-formed 'flush' pseudo clause.
9201 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9202 SourceLocation StartLoc,
9203 SourceLocation LParenLoc,
9204 SourceLocation EndLoc);
9205 /// \brief Called on well-formed 'depend' clause.
9206 OMPClause *
9207 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9208 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9209 SourceLocation StartLoc, SourceLocation LParenLoc,
9210 SourceLocation EndLoc);
9211 /// \brief Called on well-formed 'device' clause.
9212 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9213 SourceLocation LParenLoc,
9214 SourceLocation EndLoc);
9215 /// \brief Called on well-formed 'map' clause.
9216 OMPClause *
9217 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9218 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9219 SourceLocation MapLoc, SourceLocation ColonLoc,
9220 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9221 SourceLocation LParenLoc, SourceLocation EndLoc);
9222 /// \brief Called on well-formed 'num_teams' clause.
9223 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9224 SourceLocation LParenLoc,
9225 SourceLocation EndLoc);
9226 /// \brief Called on well-formed 'thread_limit' clause.
9227 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9228 SourceLocation StartLoc,
9229 SourceLocation LParenLoc,
9230 SourceLocation EndLoc);
9231 /// \brief Called on well-formed 'priority' clause.
9232 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9233 SourceLocation LParenLoc,
9234 SourceLocation EndLoc);
9235 /// \brief Called on well-formed 'dist_schedule' clause.
9236 OMPClause *ActOnOpenMPDistScheduleClause(
9237 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9238 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9239 SourceLocation CommaLoc, SourceLocation EndLoc);
9240 /// \brief Called on well-formed 'defaultmap' clause.
9241 OMPClause *ActOnOpenMPDefaultmapClause(
9242 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9243 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9244 SourceLocation KindLoc, SourceLocation EndLoc);
9245 /// \brief Called on well-formed 'to' clause.
9246 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9247 SourceLocation StartLoc,
9248 SourceLocation LParenLoc,
9249 SourceLocation EndLoc);
9250 /// \brief Called on well-formed 'from' clause.
9251 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9252 SourceLocation StartLoc,
9253 SourceLocation LParenLoc,
9254 SourceLocation EndLoc);
9255 /// Called on well-formed 'use_device_ptr' clause.
9256 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9257 SourceLocation StartLoc,
9258 SourceLocation LParenLoc,
9259 SourceLocation EndLoc);
9260 /// Called on well-formed 'is_device_ptr' clause.
9261 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9262 SourceLocation StartLoc,
9263 SourceLocation LParenLoc,
9264 SourceLocation EndLoc);
9265
9266 /// \brief The kind of conversion being performed.
9267 enum CheckedConversionKind {
9268 /// \brief An implicit conversion.
9269 CCK_ImplicitConversion,
9270 /// \brief A C-style cast.
9271 CCK_CStyleCast,
9272 /// \brief A functional-style cast.
9273 CCK_FunctionalCast,
9274 /// \brief A cast other than a C-style cast.
9275 CCK_OtherCast
9276 };
9277
9278 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9279 /// cast. If there is already an implicit cast, merge into the existing one.
9280 /// If isLvalue, the result of the cast is an lvalue.
9281 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9282 ExprValueKind VK = VK_RValue,
9283 const CXXCastPath *BasePath = nullptr,
9284 CheckedConversionKind CCK
9285 = CCK_ImplicitConversion);
9286
9287 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9288 /// to the conversion from scalar type ScalarTy to the Boolean type.
9289 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9290
9291 /// IgnoredValueConversions - Given that an expression's result is
9292 /// syntactically ignored, perform any conversions that are
9293 /// required.
9294 ExprResult IgnoredValueConversions(Expr *E);
9295
9296 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9297 // functions and arrays to their respective pointers (C99 6.3.2.1).
9298 ExprResult UsualUnaryConversions(Expr *E);
9299
9300 /// CallExprUnaryConversions - a special case of an unary conversion
9301 /// performed on a function designator of a call expression.
9302 ExprResult CallExprUnaryConversions(Expr *E);
9303
9304 // DefaultFunctionArrayConversion - converts functions and arrays
9305 // to their respective pointers (C99 6.3.2.1).
9306 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9307
9308 // DefaultFunctionArrayLvalueConversion - converts functions and
9309 // arrays to their respective pointers and performs the
9310 // lvalue-to-rvalue conversion.
9311 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9312 bool Diagnose = true);
9313
9314 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9315 // the operand. This is DefaultFunctionArrayLvalueConversion,
9316 // except that it assumes the operand isn't of function or array
9317 // type.
9318 ExprResult DefaultLvalueConversion(Expr *E);
9319
9320 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9321 // do not have a prototype. Integer promotions are performed on each
9322 // argument, and arguments that have type float are promoted to double.
9323 ExprResult DefaultArgumentPromotion(Expr *E);
9324
9325 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9326 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9327 /// we don't have xvalues there.
9328 ExprResult TemporaryMaterializationConversion(Expr *E);
9329
9330 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9331 enum VariadicCallType {
9332 VariadicFunction,
9333 VariadicBlock,
9334 VariadicMethod,
9335 VariadicConstructor,
9336 VariadicDoesNotApply
9337 };
9338
9339 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9340 const FunctionProtoType *Proto,
9341 Expr *Fn);
9342
9343 // Used for determining in which context a type is allowed to be passed to a
9344 // vararg function.
9345 enum VarArgKind {
9346 VAK_Valid,
9347 VAK_ValidInCXX11,
9348 VAK_Undefined,
9349 VAK_MSVCUndefined,
9350 VAK_Invalid
9351 };
9352
9353 // Determines which VarArgKind fits an expression.
9354 VarArgKind isValidVarArgType(const QualType &Ty);
9355
9356 /// Check to see if the given expression is a valid argument to a variadic
9357 /// function, issuing a diagnostic if not.
9358 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9359
9360 /// Check to see if a given expression could have '.c_str()' called on it.
9361 bool hasCStrMethod(const Expr *E);
9362
9363 /// GatherArgumentsForCall - Collector argument expressions for various
9364 /// form of call prototypes.
9365 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9366 const FunctionProtoType *Proto,
9367 unsigned FirstParam, ArrayRef<Expr *> Args,
9368 SmallVectorImpl<Expr *> &AllArgs,
9369 VariadicCallType CallType = VariadicDoesNotApply,
9370 bool AllowExplicit = false,
9371 bool IsListInitialization = false);
9372
9373 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9374 // will create a runtime trap if the resulting type is not a POD type.
9375 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9376 FunctionDecl *FDecl);
9377
9378 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9379 // operands and then handles various conversions that are common to binary
9380 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9381 // routine returns the first non-arithmetic type found. The client is
9382 // responsible for emitting appropriate error diagnostics.
9383 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9384 bool IsCompAssign = false);
9385
9386 /// AssignConvertType - All of the 'assignment' semantic checks return this
9387 /// enum to indicate whether the assignment was allowed. These checks are
9388 /// done for simple assignments, as well as initialization, return from
9389 /// function, argument passing, etc. The query is phrased in terms of a
9390 /// source and destination type.
9391 enum AssignConvertType {
9392 /// Compatible - the types are compatible according to the standard.
9393 Compatible,
9394
9395 /// PointerToInt - The assignment converts a pointer to an int, which we
9396 /// accept as an extension.
9397 PointerToInt,
9398
9399 /// IntToPointer - The assignment converts an int to a pointer, which we
9400 /// accept as an extension.
9401 IntToPointer,
9402
9403 /// FunctionVoidPointer - The assignment is between a function pointer and
9404 /// void*, which the standard doesn't allow, but we accept as an extension.
9405 FunctionVoidPointer,
9406
9407 /// IncompatiblePointer - The assignment is between two pointers types that
9408 /// are not compatible, but we accept them as an extension.
9409 IncompatiblePointer,
9410
9411 /// IncompatiblePointerSign - The assignment is between two pointers types
9412 /// which point to integers which have a different sign, but are otherwise
9413 /// identical. This is a subset of the above, but broken out because it's by
9414 /// far the most common case of incompatible pointers.
9415 IncompatiblePointerSign,
9416
9417 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9418 /// c/v/r qualifiers, which we accept as an extension.
9419 CompatiblePointerDiscardsQualifiers,
9420
9421 /// IncompatiblePointerDiscardsQualifiers - The assignment
9422 /// discards qualifiers that we don't permit to be discarded,
9423 /// like address spaces.
9424 IncompatiblePointerDiscardsQualifiers,
9425
9426 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9427 /// nested pointer types, and the qualifiers other than the first two
9428 /// levels differ e.g. char ** -> const char **, but we accept them as an
9429 /// extension.
9430 IncompatibleNestedPointerQualifiers,
9431
9432 /// IncompatibleVectors - The assignment is between two vector types that
9433 /// have the same size, which we accept as an extension.
9434 IncompatibleVectors,
9435
9436 /// IntToBlockPointer - The assignment converts an int to a block
9437 /// pointer. We disallow this.
9438 IntToBlockPointer,
9439
9440 /// IncompatibleBlockPointer - The assignment is between two block
9441 /// pointers types that are not compatible.
9442 IncompatibleBlockPointer,
9443
9444 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9445 /// id type and something else (that is incompatible with it). For example,
9446 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9447 IncompatibleObjCQualifiedId,
9448
9449 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9450 /// object with __weak qualifier.
9451 IncompatibleObjCWeakRef,
9452
9453 /// Incompatible - We reject this conversion outright, it is invalid to
9454 /// represent it in the AST.
9455 Incompatible
9456 };
9457
9458 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9459 /// assignment conversion type specified by ConvTy. This returns true if the
9460 /// conversion was invalid or false if the conversion was accepted.
9461 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9462 SourceLocation Loc,
9463 QualType DstType, QualType SrcType,
9464 Expr *SrcExpr, AssignmentAction Action,
9465 bool *Complained = nullptr);
9466
9467 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9468 /// enum. If AllowMask is true, then we also allow the complement of a valid
9469 /// value, to be used as a mask.
9470 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9471 bool AllowMask) const;
9472
9473 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9474 /// integer not in the range of enum values.
9475 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9476 Expr *SrcExpr);
9477
9478 /// CheckAssignmentConstraints - Perform type checking for assignment,
9479 /// argument passing, variable initialization, and function return values.
9480 /// C99 6.5.16.
9481 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9482 QualType LHSType,
9483 QualType RHSType);
9484
9485 /// Check assignment constraints and optionally prepare for a conversion of
9486 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9487 /// is true.
9488 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9489 ExprResult &RHS,
9490 CastKind &Kind,
9491 bool ConvertRHS = true);
9492
9493 /// Check assignment constraints for an assignment of RHS to LHSType.
9494 ///
9495 /// \param LHSType The destination type for the assignment.
9496 /// \param RHS The source expression for the assignment.
9497 /// \param Diagnose If \c true, diagnostics may be produced when checking
9498 /// for assignability. If a diagnostic is produced, \p RHS will be
9499 /// set to ExprError(). Note that this function may still return
9500 /// without producing a diagnostic, even for an invalid assignment.
9501 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9502 /// in an audited Core Foundation API and does not need to be checked
9503 /// for ARC retain issues.
9504 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9505 /// conversions necessary to perform the assignment. If \c false,
9506 /// \p Diagnose must also be \c false.
9507 AssignConvertType CheckSingleAssignmentConstraints(
9508 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9509 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9510
9511 // \brief If the lhs type is a transparent union, check whether we
9512 // can initialize the transparent union with the given expression.
9513 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9514 ExprResult &RHS);
9515
9516 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9517
9518 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9519
9520 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9521 AssignmentAction Action,
9522 bool AllowExplicit = false);
9523 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9524 AssignmentAction Action,
9525 bool AllowExplicit,
9526 ImplicitConversionSequence& ICS);
9527 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9528 const ImplicitConversionSequence& ICS,
9529 AssignmentAction Action,
9530 CheckedConversionKind CCK
9531 = CCK_ImplicitConversion);
9532 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9533 const StandardConversionSequence& SCS,
9534 AssignmentAction Action,
9535 CheckedConversionKind CCK);
9536
9537 /// the following "Check" methods will return a valid/converted QualType
9538 /// or a null QualType (indicating an error diagnostic was issued).
9539
9540 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9541 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9542 ExprResult &RHS);
9543 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9544 ExprResult &RHS);
9545 QualType CheckPointerToMemberOperands( // C++ 5.5
9546 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9547 SourceLocation OpLoc, bool isIndirect);
9548 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9549 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9550 bool IsDivide);
9551 QualType CheckRemainderOperands( // C99 6.5.5
9552 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9553 bool IsCompAssign = false);
9554 QualType CheckAdditionOperands( // C99 6.5.6
9555 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9556 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9557 QualType CheckSubtractionOperands( // C99 6.5.6
9558 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9559 QualType* CompLHSTy = nullptr);
9560 QualType CheckShiftOperands( // C99 6.5.7
9561 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9562 BinaryOperatorKind Opc, bool IsCompAssign = false);
9563 QualType CheckCompareOperands( // C99 6.5.8/9
9564 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9565 BinaryOperatorKind Opc, bool isRelational);
9566 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9567 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9568 BinaryOperatorKind Opc);
9569 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9570 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9571 BinaryOperatorKind Opc);
9572 // CheckAssignmentOperands is used for both simple and compound assignment.
9573 // For simple assignment, pass both expressions and a null converted type.
9574 // For compound assignment, pass both expressions and the converted type.
9575 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9576 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9577
9578 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9579 UnaryOperatorKind Opcode, Expr *Op);
9580 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9581 BinaryOperatorKind Opcode,
9582 Expr *LHS, Expr *RHS);
9583 ExprResult checkPseudoObjectRValue(Expr *E);
9584 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9585
9586 QualType CheckConditionalOperands( // C99 6.5.15
9587 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9588 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9589 QualType CXXCheckConditionalOperands( // C++ 5.16
9590 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9591 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9592 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9593 bool ConvertArgs = true);
9594 QualType FindCompositePointerType(SourceLocation Loc,
9595 ExprResult &E1, ExprResult &E2,
9596 bool ConvertArgs = true) {
9597 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9598 QualType Composite =
9599 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9600 E1 = E1Tmp;
9601 E2 = E2Tmp;
9602 return Composite;
9603 }
9604
9605 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9606 SourceLocation QuestionLoc);
9607
9608 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9609 SourceLocation QuestionLoc);
9610
9611 void DiagnoseAlwaysNonNullPointer(Expr *E,
9612 Expr::NullPointerConstantKind NullType,
9613 bool IsEqual, SourceRange Range);
9614
9615 /// type checking for vector binary operators.
9616 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9617 SourceLocation Loc, bool IsCompAssign,
9618 bool AllowBothBool, bool AllowBoolConversion);
9619 QualType GetSignedVectorType(QualType V);
9620 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9621 SourceLocation Loc,
9622 BinaryOperatorKind Opc);
9623 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9624 SourceLocation Loc);
9625
9626 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9627 bool isLaxVectorConversion(QualType srcType, QualType destType);
9628
9629 /// type checking declaration initializers (C99 6.7.8)
9630 bool CheckForConstantInitializer(Expr *e, QualType t);
9631
9632 // type checking C++ declaration initializers (C++ [dcl.init]).
9633
9634 /// ReferenceCompareResult - Expresses the result of comparing two
9635 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9636 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9637 enum ReferenceCompareResult {
9638 /// Ref_Incompatible - The two types are incompatible, so direct
9639 /// reference binding is not possible.
9640 Ref_Incompatible = 0,
9641 /// Ref_Related - The two types are reference-related, which means
9642 /// that their unqualified forms (T1 and T2) are either the same
9643 /// or T1 is a base class of T2.
9644 Ref_Related,
9645 /// Ref_Compatible - The two types are reference-compatible.
9646 Ref_Compatible
9647 };
9648
9649 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9650 QualType T1, QualType T2,
9651 bool &DerivedToBase,
9652 bool &ObjCConversion,
9653 bool &ObjCLifetimeConversion);
9654
9655 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9656 Expr *CastExpr, CastKind &CastKind,
9657 ExprValueKind &VK, CXXCastPath &Path);
9658
9659 /// \brief Force an expression with unknown-type to an expression of the
9660 /// given type.
9661 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9662
9663 /// \brief Type-check an expression that's being passed to an
9664 /// __unknown_anytype parameter.
9665 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9666 Expr *result, QualType &paramType);
9667
9668 // CheckVectorCast - check type constraints for vectors.
9669 // Since vectors are an extension, there are no C standard reference for this.
9670 // We allow casting between vectors and integer datatypes of the same size.
9671 // returns true if the cast is invalid
9672 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9673 CastKind &Kind);
9674
9675 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9676 /// implicit casts if necessary.
9677 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9678
9679 // CheckExtVectorCast - check type constraints for extended vectors.
9680 // Since vectors are an extension, there are no C standard reference for this.
9681 // We allow casting between vectors and integer datatypes of the same size,
9682 // or vectors and the element type of that vector.
9683 // returns the cast expr
9684 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9685 CastKind &Kind);
9686
9687 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9688 SourceLocation LParenLoc,
9689 Expr *CastExpr,
9690 SourceLocation RParenLoc);
9691
9692 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9693
9694 /// \brief Checks for invalid conversions and casts between
9695 /// retainable pointers and other pointer kinds for ARC and Weak.
9696 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9697 QualType castType, Expr *&op,
9698 CheckedConversionKind CCK,
9699 bool Diagnose = true,
9700 bool DiagnoseCFAudited = false,
9701 BinaryOperatorKind Opc = BO_PtrMemD
9702 );
9703
9704 Expr *stripARCUnbridgedCast(Expr *e);
9705 void diagnoseARCUnbridgedCast(Expr *e);
9706
9707 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9708 QualType ExprType);
9709
9710 /// checkRetainCycles - Check whether an Objective-C message send
9711 /// might create an obvious retain cycle.
9712 void checkRetainCycles(ObjCMessageExpr *msg);
9713 void checkRetainCycles(Expr *receiver, Expr *argument);
9714 void checkRetainCycles(VarDecl *Var, Expr *Init);
9715
9716 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9717 /// to weak/__unsafe_unretained type.
9718 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9719
9720 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9721 /// to weak/__unsafe_unretained expression.
9722 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9723
9724 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9725 /// \param Method - May be null.
9726 /// \param [out] ReturnType - The return type of the send.
9727 /// \return true iff there were any incompatible types.
9728 bool CheckMessageArgumentTypes(QualType ReceiverType,
9729 MultiExprArg Args, Selector Sel,
9730 ArrayRef<SourceLocation> SelectorLocs,
9731 ObjCMethodDecl *Method, bool isClassMessage,
9732 bool isSuperMessage,
9733 SourceLocation lbrac, SourceLocation rbrac,
9734 SourceRange RecRange,
9735 QualType &ReturnType, ExprValueKind &VK);
9736
9737 /// \brief Determine the result of a message send expression based on
9738 /// the type of the receiver, the method expected to receive the message,
9739 /// and the form of the message send.
9740 QualType getMessageSendResultType(QualType ReceiverType,
9741 ObjCMethodDecl *Method,
9742 bool isClassMessage, bool isSuperMessage);
9743
9744 /// \brief If the given expression involves a message send to a method
9745 /// with a related result type, emit a note describing what happened.
9746 void EmitRelatedResultTypeNote(const Expr *E);
9747
9748 /// \brief Given that we had incompatible pointer types in a return
9749 /// statement, check whether we're in a method with a related result
9750 /// type, and if so, emit a note describing what happened.
9751 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9752
9753 class ConditionResult {
9754 Decl *ConditionVar;
9755 FullExprArg Condition;
9756 bool Invalid;
9757 bool HasKnownValue;
9758 bool KnownValue;
9759
9760 friend class Sema;
9761 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9762 bool IsConstexpr)
9763 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9764 HasKnownValue(IsConstexpr && Condition.get() &&
9765 !Condition.get()->isValueDependent()),
9766 KnownValue(HasKnownValue &&
9767 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9768 explicit ConditionResult(bool Invalid)
9769 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9770 HasKnownValue(false), KnownValue(false) {}
9771
9772 public:
9773 ConditionResult() : ConditionResult(false) {}
9774 bool isInvalid() const { return Invalid; }
9775 std::pair<VarDecl *, Expr *> get() const {
9776 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9777 Condition.get());
9778 }
9779 llvm::Optional<bool> getKnownValue() const {
9780 if (!HasKnownValue)
9781 return None;
9782 return KnownValue;
9783 }
9784 };
9785 static ConditionResult ConditionError() { return ConditionResult(true); }
9786
9787 enum class ConditionKind {
9788 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9789 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9790 Switch ///< An integral condition for a 'switch' statement.
9791 };
9792
9793 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9794 Expr *SubExpr, ConditionKind CK);
9795
9796 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9797 SourceLocation StmtLoc,
9798 ConditionKind CK);
9799
9800 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9801
9802 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9803 SourceLocation StmtLoc,
9804 ConditionKind CK);
9805 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9806
9807 /// CheckBooleanCondition - Diagnose problems involving the use of
9808 /// the given expression as a boolean condition (e.g. in an if
9809 /// statement). Also performs the standard function and array
9810 /// decays, possibly changing the input variable.
9811 ///
9812 /// \param Loc - A location associated with the condition, e.g. the
9813 /// 'if' keyword.
9814 /// \return true iff there were any errors
9815 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9816 bool IsConstexpr = false);
9817
9818 /// DiagnoseAssignmentAsCondition - Given that an expression is
9819 /// being used as a boolean condition, warn if it's an assignment.
9820 void DiagnoseAssignmentAsCondition(Expr *E);
9821
9822 /// \brief Redundant parentheses over an equality comparison can indicate
9823 /// that the user intended an assignment used as condition.
9824 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9825
9826 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9827 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9828
9829 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9830 /// the specified width and sign. If an overflow occurs, detect it and emit
9831 /// the specified diagnostic.
9832 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9833 unsigned NewWidth, bool NewSign,
9834 SourceLocation Loc, unsigned DiagID);
9835
9836 /// Checks that the Objective-C declaration is declared in the global scope.
9837 /// Emits an error and marks the declaration as invalid if it's not declared
9838 /// in the global scope.
9839 bool CheckObjCDeclScope(Decl *D);
9840
9841 /// \brief Abstract base class used for diagnosing integer constant
9842 /// expression violations.
9843 class VerifyICEDiagnoser {
9844 public:
9845 bool Suppress;
9846
9847 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9848
9849 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9850 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9851 virtual ~VerifyICEDiagnoser() { }
9852 };
9853
9854 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9855 /// and reports the appropriate diagnostics. Returns false on success.
9856 /// Can optionally return the value of the expression.
9857 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9858 VerifyICEDiagnoser &Diagnoser,
9859 bool AllowFold = true);
9860 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9861 unsigned DiagID,
9862 bool AllowFold = true);
9863 ExprResult VerifyIntegerConstantExpression(Expr *E,
9864 llvm::APSInt *Result = nullptr);
9865
9866 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9867 /// the correct width, and that the field type is valid.
9868 /// Returns false on success.
9869 /// Can optionally return whether the bit-field is of width 0
9870 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9871 QualType FieldTy, bool IsMsStruct,
9872 Expr *BitWidth, bool *ZeroWidth = nullptr);
9873
9874private:
9875 unsigned ForceCUDAHostDeviceDepth = 0;
9876
9877public:
9878 /// Increments our count of the number of times we've seen a pragma forcing
9879 /// functions to be __host__ __device__. So long as this count is greater
9880 /// than zero, all functions encountered will be __host__ __device__.
9881 void PushForceCUDAHostDevice();
9882
9883 /// Decrements our count of the number of times we've seen a pragma forcing
9884 /// functions to be __host__ __device__. Returns false if the count is 0
9885 /// before incrementing, so you can emit an error.
9886 bool PopForceCUDAHostDevice();
9887
9888 /// Diagnostics that are emitted only if we discover that the given function
9889 /// must be codegen'ed. Because handling these correctly adds overhead to
9890 /// compilation, this is currently only enabled for CUDA compilations.
9891 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9892 std::vector<PartialDiagnosticAt>>
9893 CUDADeferredDiags;
9894
9895 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9896 /// key in a hashtable, both the FD and location are hashed.
9897 struct FunctionDeclAndLoc {
9898 CanonicalDeclPtr<FunctionDecl> FD;
9899 SourceLocation Loc;
9900 };
9901
9902 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9903 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9904 /// same deferred diag twice.
9905 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9906
9907 /// An inverse call graph, mapping known-emitted functions to one of their
9908 /// known-emitted callers (plus the location of the call).
9909 ///
9910 /// Functions that we can tell a priori must be emitted aren't added to this
9911 /// map.
9912 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9913 /* Caller = */ FunctionDeclAndLoc>
9914 CUDAKnownEmittedFns;
9915
9916 /// A partial call graph maintained during CUDA compilation to support
9917 /// deferred diagnostics.
9918 ///
9919 /// Functions are only added here if, at the time they're considered, they are
9920 /// not known-emitted. As soon as we discover that a function is
9921 /// known-emitted, we remove it and everything it transitively calls from this
9922 /// set and add those functions to CUDAKnownEmittedFns.
9923 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9924 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9925 SourceLocation>>
9926 CUDACallGraph;
9927
9928 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9929 ///
9930 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9931 /// which are not allowed to appear inside __device__ functions and are
9932 /// allowed to appear in __host__ __device__ functions only if the host+device
9933 /// function is never codegen'ed.
9934 ///
9935 /// To handle this, we use the notion of "deferred diagnostics", where we
9936 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9937 ///
9938 /// This class lets you emit either a regular diagnostic, a deferred
9939 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9940 /// its constructor, thus simplifying the process of creating these "maybe
9941 /// deferred" diagnostics.
9942 class CUDADiagBuilder {
9943 public:
9944 enum Kind {
9945 /// Emit no diagnostics.
9946 K_Nop,
9947 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9948 K_Immediate,
9949 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9950 /// emit a call stack showing how this function can be reached by an a
9951 /// priori known-emitted function.
9952 K_ImmediateWithCallStack,
9953 /// Create a deferred diagnostic, which is emitted only if the function
9954 /// it's attached to is codegen'ed. Also emit a call stack as with
9955 /// K_ImmediateWithCallStack.
9956 K_Deferred
9957 };
9958
9959 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9960 FunctionDecl *Fn, Sema &S);
9961 ~CUDADiagBuilder();
9962
9963 /// Convertible to bool: True if we immediately emitted an error, false if
9964 /// we didn't emit an error or we created a deferred error.
9965 ///
9966 /// Example usage:
9967 ///
9968 /// if (CUDADiagBuilder(...) << foo << bar)
9969 /// return ExprError();
9970 ///
9971 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9972 /// want to use these instead of creating a CUDADiagBuilder yourself.
9973 operator bool() const { return ImmediateDiag.hasValue(); }
9974
9975 template <typename T>
9976 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9977 const T &Value) {
9978 if (Diag.ImmediateDiag.hasValue())
5
Assuming the condition is false
6
Taking false branch
9979 *Diag.ImmediateDiag << Value;
9980 else if (Diag.PartialDiag.hasValue())
7
Assuming the condition is true
8
Taking true branch
9981 *Diag.PartialDiag << Value;
9
Calling 'operator<<'
20
Returned allocated memory
9982 return Diag;
9983 }
9984
9985 private:
9986 Sema &S;
9987 SourceLocation Loc;
9988 unsigned DiagID;
9989 FunctionDecl *Fn;
9990 bool ShowCallStack;
9991
9992 // Invariant: At most one of these Optionals has a value.
9993 // FIXME: Switch these to a Variant once that exists.
9994 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9995 llvm::Optional<PartialDiagnostic> PartialDiag;
9996 };
9997
9998 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9999 /// is "used as device code".
10000 ///
10001 /// - If CurContext is a __host__ function, does not emit any diagnostics.
10002 /// - If CurContext is a __device__ or __global__ function, emits the
10003 /// diagnostics immediately.
10004 /// - If CurContext is a __host__ __device__ function and we are compiling for
10005 /// the device, creates a diagnostic which is emitted if and when we realize
10006 /// that the function will be codegen'ed.
10007 ///
10008 /// Example usage:
10009 ///
10010 /// // Variable-length arrays are not allowed in CUDA device code.
10011 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
10012 /// return ExprError();
10013 /// // Otherwise, continue parsing as normal.
10014 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
10015
10016 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
10017 /// is "used as host code".
10018 ///
10019 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
10020 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
10021
10022 enum CUDAFunctionTarget {
10023 CFT_Device,
10024 CFT_Global,
10025 CFT_Host,
10026 CFT_HostDevice,
10027 CFT_InvalidTarget
10028 };
10029
10030 /// Determines whether the given function is a CUDA device/host/kernel/etc.
10031 /// function.
10032 ///
10033 /// Use this rather than examining the function's attributes yourself -- you
10034 /// will get it wrong. Returns CFT_Host if D is null.
10035 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
10036 bool IgnoreImplicitHDAttr = false);
10037 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
10038
10039 /// Gets the CUDA target for the current context.
10040 CUDAFunctionTarget CurrentCUDATarget() {
10041 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
10042 }
10043
10044 // CUDA function call preference. Must be ordered numerically from
10045 // worst to best.
10046 enum CUDAFunctionPreference {
10047 CFP_Never, // Invalid caller/callee combination.
10048 CFP_WrongSide, // Calls from host-device to host or device
10049 // function that do not match current compilation
10050 // mode.
10051 CFP_HostDevice, // Any calls to host/device functions.
10052 CFP_SameSide, // Calls from host-device to host or device
10053 // function matching current compilation mode.
10054 CFP_Native, // host-to-host or device-to-device calls.
10055 };
10056
10057 /// Identifies relative preference of a given Caller/Callee
10058 /// combination, based on their host/device attributes.
10059 /// \param Caller function which needs address of \p Callee.
10060 /// nullptr in case of global context.
10061 /// \param Callee target function
10062 ///
10063 /// \returns preference value for particular Caller/Callee combination.
10064 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
10065 const FunctionDecl *Callee);
10066
10067 /// Determines whether Caller may invoke Callee, based on their CUDA
10068 /// host/device attributes. Returns false if the call is not allowed.
10069 ///
10070 /// Note: Will return true for CFP_WrongSide calls. These may appear in
10071 /// semantically correct CUDA programs, but only if they're never codegen'ed.
10072 bool IsAllowedCUDACall(const FunctionDecl *Caller,
10073 const FunctionDecl *Callee) {
10074 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
10075 }
10076
10077 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
10078 /// depending on FD and the current compilation settings.
10079 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
10080 const LookupResult &Previous);
10081
10082public:
10083 /// Check whether we're allowed to call Callee from the current context.
10084 ///
10085 /// - If the call is never allowed in a semantically-correct program
10086 /// (CFP_Never), emits an error and returns false.
10087 ///
10088 /// - If the call is allowed in semantically-correct programs, but only if
10089 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
10090 /// be emitted if and when the caller is codegen'ed, and returns true.
10091 ///
10092 /// Will only create deferred diagnostics for a given SourceLocation once,
10093 /// so you can safely call this multiple times without generating duplicate
10094 /// deferred errors.
10095 ///
10096 /// - Otherwise, returns true without emitting any diagnostics.
10097 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
10098
10099 /// Set __device__ or __host__ __device__ attributes on the given lambda
10100 /// operator() method.
10101 ///
10102 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
10103 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
10104 /// functions become __host__ __device__ themselves.
10105 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
10106
10107 /// Finds a function in \p Matches with highest calling priority
10108 /// from \p Caller context and erases all functions with lower
10109 /// calling priority.
10110 void EraseUnwantedCUDAMatches(
10111 const FunctionDecl *Caller,
10112 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
10113
10114 /// Given a implicit special member, infer its CUDA target from the
10115 /// calls it needs to make to underlying base/field special members.
10116 /// \param ClassDecl the class for which the member is being created.
10117 /// \param CSM the kind of special member.
10118 /// \param MemberDecl the special member itself.
10119 /// \param ConstRHS true if this is a copy operation with a const object on
10120 /// its RHS.
10121 /// \param Diagnose true if this call should emit diagnostics.
10122 /// \return true if there was an error inferring.
10123 /// The result of this call is implicit CUDA target attribute(s) attached to
10124 /// the member declaration.
10125 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
10126 CXXSpecialMember CSM,
10127 CXXMethodDecl *MemberDecl,
10128 bool ConstRHS,
10129 bool Diagnose);
10130
10131 /// \return true if \p CD can be considered empty according to CUDA
10132 /// (E.2.3.1 in CUDA 7.5 Programming guide).
10133 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
10134 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
10135
10136 /// Check whether NewFD is a valid overload for CUDA. Emits
10137 /// diagnostics and invalidates NewFD if not.
10138 void checkCUDATargetOverload(FunctionDecl *NewFD,
10139 const LookupResult &Previous);
10140 /// Copies target attributes from the template TD to the function FD.
10141 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
10142
10143 /// \name Code completion
10144 //@{
10145 /// \brief Describes the context in which code completion occurs.
10146 enum ParserCompletionContext {
10147 /// \brief Code completion occurs at top-level or namespace context.
10148 PCC_Namespace,
10149 /// \brief Code completion occurs within a class, struct, or union.
10150 PCC_Class,
10151 /// \brief Code completion occurs within an Objective-C interface, protocol,
10152 /// or category.
10153 PCC_ObjCInterface,
10154 /// \brief Code completion occurs within an Objective-C implementation or
10155 /// category implementation
10156 PCC_ObjCImplementation,
10157 /// \brief Code completion occurs within the list of instance variables
10158 /// in an Objective-C interface, protocol, category, or implementation.
10159 PCC_ObjCInstanceVariableList,
10160 /// \brief Code completion occurs following one or more template
10161 /// headers.
10162 PCC_Template,
10163 /// \brief Code completion occurs following one or more template
10164 /// headers within a class.
10165 PCC_MemberTemplate,
10166 /// \brief Code completion occurs within an expression.
10167 PCC_Expression,
10168 /// \brief Code completion occurs within a statement, which may
10169 /// also be an expression or a declaration.
10170 PCC_Statement,
10171 /// \brief Code completion occurs at the beginning of the
10172 /// initialization statement (or expression) in a for loop.
10173 PCC_ForInit,
10174 /// \brief Code completion occurs within the condition of an if,
10175 /// while, switch, or for statement.
10176 PCC_Condition,
10177 /// \brief Code completion occurs within the body of a function on a
10178 /// recovery path, where we do not have a specific handle on our position
10179 /// in the grammar.
10180 PCC_RecoveryInFunction,
10181 /// \brief Code completion occurs where only a type is permitted.
10182 PCC_Type,
10183 /// \brief Code completion occurs in a parenthesized expression, which
10184 /// might also be a type cast.
10185 PCC_ParenthesizedExpression,
10186 /// \brief Code completion occurs within a sequence of declaration
10187 /// specifiers within a function, method, or block.
10188 PCC_LocalDeclarationSpecifiers
10189 };
10190
10191 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10192 void CodeCompleteOrdinaryName(Scope *S,
10193 ParserCompletionContext CompletionContext);
10194 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10195 bool AllowNonIdentifiers,
10196 bool AllowNestedNameSpecifiers);
10197
10198 struct CodeCompleteExpressionData;
10199 void CodeCompleteExpression(Scope *S,
10200 const CodeCompleteExpressionData &Data);
10201 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
10202 SourceLocation OpLoc, bool IsArrow,
10203 bool IsBaseExprStatement);
10204 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10205 void CodeCompleteTag(Scope *S, unsigned TagSpec);
10206 void CodeCompleteTypeQualifiers(DeclSpec &DS);
10207 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10208 const VirtSpecifiers *VS = nullptr);
10209 void CodeCompleteBracketDeclarator(Scope *S);
10210 void CodeCompleteCase(Scope *S);
10211 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10212 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10213 ArrayRef<Expr *> Args);
10214 void CodeCompleteInitializer(Scope *S, Decl *D);
10215 void CodeCompleteReturn(Scope *S);
10216 void CodeCompleteAfterIf(Scope *S);
10217 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10218
10219 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10220 bool EnteringContext);
10221 void CodeCompleteUsing(Scope *S);
10222 void CodeCompleteUsingDirective(Scope *S);
10223 void CodeCompleteNamespaceDecl(Scope *S);
10224 void CodeCompleteNamespaceAliasDecl(Scope *S);
10225 void CodeCompleteOperatorName(Scope *S);
10226 void CodeCompleteConstructorInitializer(
10227 Decl *Constructor,
10228 ArrayRef<CXXCtorInitializer *> Initializers);
10229
10230 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10231 bool AfterAmpersand);
10232
10233 void CodeCompleteObjCAtDirective(Scope *S);
10234 void CodeCompleteObjCAtVisibility(Scope *S);
10235 void CodeCompleteObjCAtStatement(Scope *S);
10236 void CodeCompleteObjCAtExpression(Scope *S);
10237 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10238 void CodeCompleteObjCPropertyGetter(Scope *S);
10239 void CodeCompleteObjCPropertySetter(Scope *S);
10240 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10241 bool IsParameter);
10242 void CodeCompleteObjCMessageReceiver(Scope *S);
10243 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10244 ArrayRef<IdentifierInfo *> SelIdents,
10245 bool AtArgumentExpression);
10246 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10247 ArrayRef<IdentifierInfo *> SelIdents,
10248 bool AtArgumentExpression,
10249 bool IsSuper = false);
10250 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10251 ArrayRef<IdentifierInfo *> SelIdents,
10252 bool AtArgumentExpression,
10253 ObjCInterfaceDecl *Super = nullptr);
10254 void CodeCompleteObjCForCollection(Scope *S,
10255 DeclGroupPtrTy IterationVar);
10256 void CodeCompleteObjCSelector(Scope *S,
10257 ArrayRef<IdentifierInfo *> SelIdents);
10258 void CodeCompleteObjCProtocolReferences(
10259 ArrayRef<IdentifierLocPair> Protocols);
10260 void CodeCompleteObjCProtocolDecl(Scope *S);
10261 void CodeCompleteObjCInterfaceDecl(Scope *S);
10262 void CodeCompleteObjCSuperclass(Scope *S,
10263 IdentifierInfo *ClassName,
10264 SourceLocation ClassNameLoc);
10265 void CodeCompleteObjCImplementationDecl(Scope *S);
10266 void CodeCompleteObjCInterfaceCategory(Scope *S,
10267 IdentifierInfo *ClassName,
10268 SourceLocation ClassNameLoc);
10269 void CodeCompleteObjCImplementationCategory(Scope *S,
10270 IdentifierInfo *ClassName,
10271 SourceLocation ClassNameLoc);
10272 void CodeCompleteObjCPropertyDefinition(Scope *S);
10273 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10274 IdentifierInfo *PropertyName);
10275 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
10276 ParsedType ReturnType);
10277 void CodeCompleteObjCMethodDeclSelector(Scope *S,
10278 bool IsInstanceMethod,
10279 bool AtParameterName,
10280 ParsedType ReturnType,
10281 ArrayRef<IdentifierInfo *> SelIdents);
10282 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10283 SourceLocation ClassNameLoc,
10284 bool IsBaseExprStatement);
10285 void CodeCompletePreprocessorDirective(bool InConditional);
10286 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10287 void CodeCompletePreprocessorMacroName(bool IsDefinition);
10288 void CodeCompletePreprocessorExpression();
10289 void CodeCompletePreprocessorMacroArgument(Scope *S,
10290 IdentifierInfo *Macro,
10291 MacroInfo *MacroInfo,
10292 unsigned Argument);
10293 void CodeCompleteNaturalLanguage();
10294 void CodeCompleteAvailabilityPlatformName();
10295 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10296 CodeCompletionTUInfo &CCTUInfo,
10297 SmallVectorImpl<CodeCompletionResult> &Results);
10298 //@}
10299
10300 //===--------------------------------------------------------------------===//
10301 // Extra semantic analysis beyond the C type system
10302
10303public:
10304 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10305 unsigned ByteNo) const;
10306
10307private:
10308 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10309 const ArraySubscriptExpr *ASE=nullptr,
10310 bool AllowOnePastEnd=true, bool IndexNegated=false);
10311 void CheckArrayAccess(const Expr *E);
10312 // Used to grab the relevant information from a FormatAttr and a
10313 // FunctionDeclaration.
10314 struct FormatStringInfo {
10315 unsigned FormatIdx;
10316 unsigned FirstDataArg;
10317 bool HasVAListArg;
10318 };
10319
10320 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10321 FormatStringInfo *FSI);
10322 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10323 const FunctionProtoType *Proto);
10324 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10325 ArrayRef<const Expr *> Args);
10326 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10327 const FunctionProtoType *Proto);
10328 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10329 void CheckConstructorCall(FunctionDecl *FDecl,
10330 ArrayRef<const Expr *> Args,
10331 const FunctionProtoType *Proto,
10332 SourceLocation Loc);
10333
10334 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10335 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10336 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10337 VariadicCallType CallType);
10338
10339 bool CheckObjCString(Expr *Arg);
10340 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10341
10342 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10343 unsigned BuiltinID, CallExpr *TheCall);
10344
10345 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10346 unsigned MaxWidth);
10347 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10348 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10349
10350 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10351 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10352 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10353 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10354 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10355 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10356 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10357
10358 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10359 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
10360 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10361 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10362 bool SemaBuiltinVSX(CallExpr *TheCall);
10363 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10364
10365public:
10366 // Used by C++ template instantiation.
10367 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10368 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10369 SourceLocation BuiltinLoc,
10370 SourceLocation RParenLoc);
10371
10372private:
10373 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10374 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10375 bool SemaBuiltinAssume(CallExpr *TheCall);
10376 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10377 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10378 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10379 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10380 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10381 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10382 AtomicExpr::AtomicOp Op);
10383 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10384 llvm::APSInt &Result);
10385 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10386 int Low, int High);
10387 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10388 unsigned Multiple);
10389 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10390 int ArgNum, unsigned ExpectedFieldNum,
10391 bool AllowName);
10392public:
10393 enum FormatStringType {
10394 FST_Scanf,
10395 FST_Printf,
10396 FST_NSString,
10397 FST_Strftime,
10398 FST_Strfmon,
10399 FST_Kprintf,
10400 FST_FreeBSDKPrintf,
10401 FST_OSTrace,
10402 FST_OSLog,
10403 FST_Unknown
10404 };
10405 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10406
10407 bool FormatStringHasSArg(const StringLiteral *FExpr);
10408
10409 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10410
10411private:
10412 bool CheckFormatArguments(const FormatAttr *Format,
10413 ArrayRef<const Expr *> Args,
10414 bool IsCXXMember,
10415 VariadicCallType CallType,
10416 SourceLocation Loc, SourceRange Range,
10417 llvm::SmallBitVector &CheckedVarArgs);
10418 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10419 bool HasVAListArg, unsigned format_idx,
10420 unsigned firstDataArg, FormatStringType Type,
10421 VariadicCallType CallType,
10422 SourceLocation Loc, SourceRange range,
10423 llvm::SmallBitVector &CheckedVarArgs);
10424
10425 void CheckAbsoluteValueFunction(const CallExpr *Call,
10426 const FunctionDecl *FDecl);
10427
10428 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10429
10430 void CheckMemaccessArguments(const CallExpr *Call,
10431 unsigned BId,
10432 IdentifierInfo *FnName);
10433
10434 void CheckStrlcpycatArguments(const CallExpr *Call,
10435 IdentifierInfo *FnName);
10436
10437 void CheckStrncatArguments(const CallExpr *Call,
10438 IdentifierInfo *FnName);
10439
10440 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10441 SourceLocation ReturnLoc,
10442 bool isObjCMethod = false,
10443 const AttrVec *Attrs = nullptr,
10444 const FunctionDecl *FD = nullptr);
10445
10446public:
10447 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
10448
10449private:
10450 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10451 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10452 void CheckForIntOverflow(Expr *E);
10453 void CheckUnsequencedOperations(Expr *E);
10454
10455 /// \brief Perform semantic checks on a completed expression. This will either
10456 /// be a full-expression or a default argument expression.
10457 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10458 bool IsConstexpr = false);
10459
10460 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10461 Expr *Init);
10462
10463 /// Check if there is a field shadowing.
10464 void CheckShadowInheritedFields(const SourceLocation &Loc,
10465 DeclarationName FieldName,
10466 const CXXRecordDecl *RD);
10467
10468 /// \brief Check if the given expression contains 'break' or 'continue'
10469 /// statement that produces control flow different from GCC.
10470 void CheckBreakContinueBinding(Expr *E);
10471
10472 /// \brief Check whether receiver is mutable ObjC container which
10473 /// attempts to add itself into the container
10474 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10475
10476 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10477 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10478 bool DeleteWasArrayForm);
10479public:
10480 /// \brief Register a magic integral constant to be used as a type tag.
10481 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10482 uint64_t MagicValue, QualType Type,
10483 bool LayoutCompatible, bool MustBeNull);
10484
10485 struct TypeTagData {
10486 TypeTagData() {}
10487
10488 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10489 Type(Type), LayoutCompatible(LayoutCompatible),
10490 MustBeNull(MustBeNull)
10491 {}
10492
10493 QualType Type;
10494
10495 /// If true, \c Type should be compared with other expression's types for
10496 /// layout-compatibility.
10497 unsigned LayoutCompatible : 1;
10498 unsigned MustBeNull : 1;
10499 };
10500
10501 /// A pair of ArgumentKind identifier and magic value. This uniquely
10502 /// identifies the magic value.
10503 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10504
10505private:
10506 /// \brief A map from magic value to type information.
10507 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10508 TypeTagForDatatypeMagicValues;
10509
10510 /// \brief Peform checks on a call of a function with argument_with_type_tag
10511 /// or pointer_with_type_tag attributes.
10512 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10513 const ArrayRef<const Expr *> ExprArgs,
10514 SourceLocation CallSiteLoc);
10515
10516 /// \brief Check if we are taking the address of a packed field
10517 /// as this may be a problem if the pointer value is dereferenced.
10518 void CheckAddressOfPackedMember(Expr *rhs);
10519
10520 /// \brief The parser's current scope.
10521 ///
10522 /// The parser maintains this state here.
10523 Scope *CurScope;
10524
10525 mutable IdentifierInfo *Ident_super;
10526 mutable IdentifierInfo *Ident___float128;
10527
10528 /// Nullability type specifiers.
10529 IdentifierInfo *Ident__Nonnull = nullptr;
10530 IdentifierInfo *Ident__Nullable = nullptr;
10531 IdentifierInfo *Ident__Null_unspecified = nullptr;
10532
10533 IdentifierInfo *Ident_NSError = nullptr;
10534
10535 /// \brief The handler for the FileChanged preprocessor events.
10536 ///
10537 /// Used for diagnostics that implement custom semantic analysis for #include
10538 /// directives, like -Wpragma-pack.
10539 sema::SemaPPCallbacks *SemaPPCallbackHandler;
10540
10541protected:
10542 friend class Parser;
10543 friend class InitializationSequence;
10544 friend class ASTReader;
10545 friend class ASTDeclReader;
10546 friend class ASTWriter;
10547
10548public:
10549 /// Retrieve the keyword associated
10550 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10551
10552 /// The struct behind the CFErrorRef pointer.
10553 RecordDecl *CFError = nullptr;
10554
10555 /// Retrieve the identifier "NSError".
10556 IdentifierInfo *getNSErrorIdent();
10557
10558 /// \brief Retrieve the parser's current scope.
10559 ///
10560 /// This routine must only be used when it is certain that semantic analysis
10561 /// and the parser are in precisely the same context, which is not the case
10562 /// when, e.g., we are performing any kind of template instantiation.
10563 /// Therefore, the only safe places to use this scope are in the parser
10564 /// itself and in routines directly invoked from the parser and *never* from
10565 /// template substitution or instantiation.
10566 Scope *getCurScope() const { return CurScope; }
10567
10568 void incrementMSManglingNumber() const {
10569 return CurScope->incrementMSManglingNumber();
10570 }
10571
10572 IdentifierInfo *getSuperIdentifier() const;
10573 IdentifierInfo *getFloat128Identifier() const;
10574
10575 Decl *getObjCDeclContext() const;
10576
10577 DeclContext *getCurLexicalContext() const {
10578 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10579 }
10580
10581 const DeclContext *getCurObjCLexicalContext() const {
10582 const DeclContext *DC = getCurLexicalContext();
10583 // A category implicitly has the attribute of the interface.
10584 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10585 DC = CatD->getClassInterface();
10586 return DC;
10587 }
10588
10589 /// \brief To be used for checking whether the arguments being passed to
10590 /// function exceeds the number of parameters expected for it.
10591 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10592 bool PartialOverloading = false) {
10593 // We check whether we're just after a comma in code-completion.
10594 if (NumArgs > 0 && PartialOverloading)
10595 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10596 return NumArgs > NumParams;
10597 }
10598
10599 // Emitting members of dllexported classes is delayed until the class
10600 // (including field initializers) is fully parsed.
10601 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10602
10603private:
10604 class SavePendingParsedClassStateRAII {
10605 public:
10606 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
10607
10608 ~SavePendingParsedClassStateRAII() {
10609 assert(S.DelayedExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 10610, __extension__ __PRETTY_FUNCTION__))
10610 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedExceptionSpecChecks.empty
() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 10610, __extension__ __PRETTY_FUNCTION__))
;
10611 assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 10613, __extension__ __PRETTY_FUNCTION__))
10612 "there shouldn't be any pending delayed defaulted member "(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 10613, __extension__ __PRETTY_FUNCTION__))
10613 "exception specs")(static_cast <bool> (S.DelayedDefaultedMemberExceptionSpecs
.empty() && "there shouldn't be any pending delayed defaulted member "
"exception specs") ? void (0) : __assert_fail ("S.DelayedDefaultedMemberExceptionSpecs.empty() && \"there shouldn't be any pending delayed defaulted member \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 10613, __extension__ __PRETTY_FUNCTION__))
;
10614 assert(S.DelayedDllExportClasses.empty() &&(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 10615, __extension__ __PRETTY_FUNCTION__))
10615 "there shouldn't be any pending delayed DLL export classes")(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes")
? void (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"there shouldn't be any pending delayed DLL export classes\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 10615, __extension__ __PRETTY_FUNCTION__))
;
10616 swapSavedState();
10617 }
10618
10619 private:
10620 Sema &S;
10621 decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks;
10622 decltype(DelayedDefaultedMemberExceptionSpecs)
10623 SavedDefaultedMemberExceptionSpecs;
10624 decltype(DelayedDllExportClasses) SavedDllExportClasses;
10625
10626 void swapSavedState() {
10627 SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks);
10628 SavedDefaultedMemberExceptionSpecs.swap(
10629 S.DelayedDefaultedMemberExceptionSpecs);
10630 SavedDllExportClasses.swap(S.DelayedDllExportClasses);
10631 }
10632 };
10633
10634 /// \brief Helper class that collects misaligned member designations and
10635 /// their location info for delayed diagnostics.
10636 struct MisalignedMember {
10637 Expr *E;
10638 RecordDecl *RD;
10639 ValueDecl *MD;
10640 CharUnits Alignment;
10641
10642 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10643 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10644 CharUnits Alignment)
10645 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10646 explicit MisalignedMember(Expr *E)
10647 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10648
10649 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10650 };
10651 /// \brief Small set of gathered accesses to potentially misaligned members
10652 /// due to the packed attribute.
10653 SmallVector<MisalignedMember, 4> MisalignedMembers;
10654
10655 /// \brief Adds an expression to the set of gathered misaligned members.
10656 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10657 CharUnits Alignment);
10658
10659public:
10660 /// \brief Diagnoses the current set of gathered accesses. This typically
10661 /// happens at full expression level. The set is cleared after emitting the
10662 /// diagnostics.
10663 void DiagnoseMisalignedMembers();
10664
10665 /// \brief This function checks if the expression is in the sef of potentially
10666 /// misaligned members and it is converted to some pointer type T with lower
10667 /// or equal alignment requirements. If so it removes it. This is used when
10668 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10669 /// void*).
10670 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10671
10672 /// \brief This function calls Action when it determines that E designates a
10673 /// misaligned member due to the packed attribute. This is used to emit
10674 /// local diagnostics like in reference binding.
10675 void RefersToMemberWithReducedAlignment(
10676 Expr *E,
10677 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10678 Action);
10679};
10680
10681/// \brief RAII object that enters a new expression evaluation context.
10682class EnterExpressionEvaluationContext {
10683 Sema &Actions;
10684 bool Entered = true;
10685
10686public:
10687
10688 EnterExpressionEvaluationContext(Sema &Actions,
10689 Sema::ExpressionEvaluationContext NewContext,
10690 Decl *LambdaContextDecl = nullptr,
10691 bool IsDecltype = false,
10692 bool ShouldEnter = true)
10693 : Actions(Actions), Entered(ShouldEnter) {
10694 if (Entered)
10695 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10696 IsDecltype);
10697 }
10698 EnterExpressionEvaluationContext(Sema &Actions,
10699 Sema::ExpressionEvaluationContext NewContext,
10700 Sema::ReuseLambdaContextDecl_t,
10701 bool IsDecltype = false)
10702 : Actions(Actions) {
10703 Actions.PushExpressionEvaluationContext(NewContext,
10704 Sema::ReuseLambdaContextDecl,
10705 IsDecltype);
10706 }
10707
10708 enum InitListTag { InitList };
10709 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10710 bool ShouldEnter = true)
10711 : Actions(Actions), Entered(false) {
10712 // In C++11 onwards, narrowing checks are performed on the contents of
10713 // braced-init-lists, even when they occur within unevaluated operands.
10714 // Therefore we still need to instantiate constexpr functions used in such
10715 // a context.
10716 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10717 Actions.getLangOpts().CPlusPlus11) {
10718 Actions.PushExpressionEvaluationContext(
10719 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10720 Entered = true;
10721 }
10722 }
10723
10724 ~EnterExpressionEvaluationContext() {
10725 if (Entered)
10726 Actions.PopExpressionEvaluationContext();
10727 }
10728};
10729
10730DeductionFailureInfo
10731MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10732 sema::TemplateDeductionInfo &Info);
10733
10734/// \brief Contains a late templated function.
10735/// Will be parsed at the end of the translation unit, used by Sema & Parser.
10736struct LateParsedTemplate {
10737 CachedTokens Toks;
10738 /// \brief The template function declaration to be late parsed.
10739 Decl *D;
10740};
10741
10742} // end namespace clang
10743
10744namespace llvm {
10745// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10746// SourceLocation.
10747template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10748 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10749 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10750
10751 static FunctionDeclAndLoc getEmptyKey() {
10752 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10753 }
10754
10755 static FunctionDeclAndLoc getTombstoneKey() {
10756 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10757 }
10758
10759 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10760 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10761 FDL.Loc.getRawEncoding());
10762 }
10763
10764 static bool isEqual(const FunctionDeclAndLoc &LHS,
10765 const FunctionDeclAndLoc &RHS) {
10766 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10767 }
10768};
10769} // namespace llvm
10770
10771#endif

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h

1//===- PartialDiagnostic.h - Diagnostic "closures" --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief Implements a partial diagnostic that can be emitted anwyhere
12/// in a DiagnosticBuilder stream.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
17#define LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H
18
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include <cassert>
25#include <cstdint>
26#include <string>
27#include <type_traits>
28#include <utility>
29
30namespace clang {
31
32class DeclContext;
33class IdentifierInfo;
34
35class PartialDiagnostic {
36public:
37 enum {
38 // The MaxArguments and MaxFixItHints member enum values from
39 // DiagnosticsEngine are private but DiagnosticsEngine declares
40 // PartialDiagnostic a friend. These enum values are redeclared
41 // here so that the nested Storage class below can access them.
42 MaxArguments = DiagnosticsEngine::MaxArguments
43 };
44
45 struct Storage {
46 enum {
47 /// \brief The maximum number of arguments we can hold. We
48 /// currently only support up to 10 arguments (%0-%9).
49 ///
50 /// A single diagnostic with more than that almost certainly has to
51 /// be simplified anyway.
52 MaxArguments = PartialDiagnostic::MaxArguments
53 };
54
55 /// \brief The number of entries in Arguments.
56 unsigned char NumDiagArgs = 0;
57
58 /// \brief Specifies for each argument whether it is in DiagArgumentsStr
59 /// or in DiagArguments.
60 unsigned char DiagArgumentsKind[MaxArguments];
61
62 /// \brief The values for the various substitution positions.
63 ///
64 /// This is used when the argument is not an std::string. The specific value
65 /// is mangled into an intptr_t and the interpretation depends on exactly
66 /// what sort of argument kind it is.
67 intptr_t DiagArgumentsVal[MaxArguments];
68
69 /// \brief The values for the various substitution positions that have
70 /// string arguments.
71 std::string DiagArgumentsStr[MaxArguments];
72
73 /// \brief The list of ranges added to this diagnostic.
74 SmallVector<CharSourceRange, 8> DiagRanges;
75
76 /// \brief If valid, provides a hint with some code to insert, remove, or
77 /// modify at a particular position.
78 SmallVector<FixItHint, 6> FixItHints;
79
80 Storage() = default;
81 };
82
83 /// \brief An allocator for Storage objects, which uses a small cache to
84 /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
85 class StorageAllocator {
86 static const unsigned NumCached = 16;
87 Storage Cached[NumCached];
88 Storage *FreeList[NumCached];
89 unsigned NumFreeListEntries;
90
91 public:
92 StorageAllocator();
93 ~StorageAllocator();
94
95 /// \brief Allocate new storage.
96 Storage *Allocate() {
97 if (NumFreeListEntries == 0)
98 return new Storage;
99
100 Storage *Result = FreeList[--NumFreeListEntries];
101 Result->NumDiagArgs = 0;
102 Result->DiagRanges.clear();
103 Result->FixItHints.clear();
104 return Result;
105 }
106
107 /// \brief Free the given storage object.
108 void Deallocate(Storage *S) {
109 if (S >= Cached && S <= Cached + NumCached) {
110 FreeList[NumFreeListEntries++] = S;
111 return;
112 }
113
114 delete S;
115 }
116 };
117
118private:
119 // NOTE: Sema assumes that PartialDiagnostic is location-invariant
120 // in the sense that its bits can be safely memcpy'ed and destructed
121 // in the new location.
122
123 /// \brief The diagnostic ID.
124 mutable unsigned DiagID = 0;
125
126 /// \brief Storage for args and ranges.
127 mutable Storage *DiagStorage = nullptr;
128
129 /// \brief Allocator used to allocate storage for this diagnostic.
130 StorageAllocator *Allocator = nullptr;
131
132 /// \brief Retrieve storage for this particular diagnostic.
133 Storage *getStorage() const {
134 if (DiagStorage)
14
Taking false branch
135 return DiagStorage;
136
137 if (Allocator)
15
Assuming the condition is false
16
Taking false branch
138 DiagStorage = Allocator->Allocate();
139 else {
140 assert(Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))(static_cast <bool> (Allocator != reinterpret_cast<StorageAllocator
*>(~uintptr_t(0))) ? void (0) : __assert_fail ("Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0))"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 140, __extension__ __PRETTY_FUNCTION__))
;
141 DiagStorage = new Storage;
17
Memory is allocated
142 }
143 return DiagStorage;
144 }
145
146 void freeStorage() {
147 if (!DiagStorage)
148 return;
149
150 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
151 // (typically so we have the flexibility of passing a more complex
152 // diagnostic into the callee, but that does not commonly occur).
153 //
154 // Split this out into a slow function for silly compilers (*cough*) which
155 // can't do decent partial inlining.
156 freeStorageSlow();
157 }
158
159 void freeStorageSlow() {
160 if (Allocator)
161 Allocator->Deallocate(DiagStorage);
162 else if (Allocator != reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))
163 delete DiagStorage;
164 DiagStorage = nullptr;
165 }
166
167 void AddSourceRange(const CharSourceRange &R) const {
168 if (!DiagStorage)
169 DiagStorage = getStorage();
170
171 DiagStorage->DiagRanges.push_back(R);
172 }
173
174 void AddFixItHint(const FixItHint &Hint) const {
175 if (Hint.isNull())
176 return;
177
178 if (!DiagStorage)
179 DiagStorage = getStorage();
180
181 DiagStorage->FixItHints.push_back(Hint);
182 }
183
184public:
185 struct NullDiagnostic {};
186
187 /// \brief Create a null partial diagnostic, which cannot carry a payload,
188 /// and only exists to be swapped with a real partial diagnostic.
189 PartialDiagnostic(NullDiagnostic) {}
190
191 PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator)
192 : DiagID(DiagID), Allocator(&Allocator) {}
193
194 PartialDiagnostic(const PartialDiagnostic &Other)
195 : DiagID(Other.DiagID), Allocator(Other.Allocator) {
196 if (Other.DiagStorage) {
197 DiagStorage = getStorage();
198 *DiagStorage = *Other.DiagStorage;
199 }
200 }
201
202 PartialDiagnostic(PartialDiagnostic &&Other)
203 : DiagID(Other.DiagID), DiagStorage(Other.DiagStorage),
204 Allocator(Other.Allocator) {
205 Other.DiagStorage = nullptr;
206 }
207
208 PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage)
209 : DiagID(Other.DiagID), DiagStorage(DiagStorage),
210 Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0))) {
211 if (Other.DiagStorage)
212 *this->DiagStorage = *Other.DiagStorage;
213 }
214
215 PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator)
216 : DiagID(Other.getID()), Allocator(&Allocator) {
217 // Copy arguments.
218 for (unsigned I = 0, N = Other.getNumArgs(); I != N; ++I) {
219 if (Other.getArgKind(I) == DiagnosticsEngine::ak_std_string)
220 AddString(Other.getArgStdStr(I));
221 else
222 AddTaggedVal(Other.getRawArg(I), Other.getArgKind(I));
223 }
224
225 // Copy source ranges.
226 for (unsigned I = 0, N = Other.getNumRanges(); I != N; ++I)
227 AddSourceRange(Other.getRange(I));
228
229 // Copy fix-its.
230 for (unsigned I = 0, N = Other.getNumFixItHints(); I != N; ++I)
231 AddFixItHint(Other.getFixItHint(I));
232 }
233
234 PartialDiagnostic &operator=(const PartialDiagnostic &Other) {
235 DiagID = Other.DiagID;
236 if (Other.DiagStorage) {
237 if (!DiagStorage)
238 DiagStorage = getStorage();
239
240 *DiagStorage = *Other.DiagStorage;
241 } else {
242 freeStorage();
243 }
244
245 return *this;
246 }
247
248 PartialDiagnostic &operator=(PartialDiagnostic &&Other) {
249 freeStorage();
250
251 DiagID = Other.DiagID;
252 DiagStorage = Other.DiagStorage;
253 Allocator = Other.Allocator;
254
255 Other.DiagStorage = nullptr;
256 return *this;
257 }
258
259 ~PartialDiagnostic() {
260 freeStorage();
261 }
262
263 void swap(PartialDiagnostic &PD) {
264 std::swap(DiagID, PD.DiagID);
265 std::swap(DiagStorage, PD.DiagStorage);
266 std::swap(Allocator, PD.Allocator);
267 }
268
269 unsigned getDiagID() const { return DiagID; }
270
271 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
272 if (!DiagStorage)
11
Assuming the condition is true
12
Taking true branch
273 DiagStorage = getStorage();
13
Calling 'PartialDiagnostic::getStorage'
18
Returned allocated memory
274
275 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 276, __extension__ __PRETTY_FUNCTION__))
276 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
278 DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
279 }
280
281 void AddString(StringRef V) const {
282 if (!DiagStorage)
283 DiagStorage = getStorage();
284
285 assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 286, __extension__ __PRETTY_FUNCTION__))
286 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < Storage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < Storage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs]
288 = DiagnosticsEngine::ak_std_string;
289 DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = V;
290 }
291
292 void Emit(const DiagnosticBuilder &DB) const {
293 if (!DiagStorage)
294 return;
295
296 // Add all arguments.
297 for (unsigned i = 0, e = DiagStorage->NumDiagArgs; i != e; ++i) {
298 if ((DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]
299 == DiagnosticsEngine::ak_std_string)
300 DB.AddString(DiagStorage->DiagArgumentsStr[i]);
301 else
302 DB.AddTaggedVal(DiagStorage->DiagArgumentsVal[i],
303 (DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[i]);
304 }
305
306 // Add all ranges.
307 for (const CharSourceRange &Range : DiagStorage->DiagRanges)
308 DB.AddSourceRange(Range);
309
310 // Add all fix-its.
311 for (const FixItHint &Fix : DiagStorage->FixItHints)
312 DB.AddFixItHint(Fix);
313 }
314
315 void EmitToString(DiagnosticsEngine &Diags,
316 SmallVectorImpl<char> &Buf) const {
317 // FIXME: It should be possible to render a diagnostic to a string without
318 // messing with the state of the diagnostics engine.
319 DiagnosticBuilder DB(Diags.Report(getDiagID()));
320 Emit(DB);
321 DB.FlushCounts();
322 Diagnostic(&Diags).FormatDiagnostic(Buf);
323 DB.Clear();
324 Diags.Clear();
325 }
326
327 /// \brief Clear out this partial diagnostic, giving it a new diagnostic ID
328 /// and removing all of its arguments, ranges, and fix-it hints.
329 void Reset(unsigned DiagID = 0) {
330 this->DiagID = DiagID;
331 freeStorage();
332 }
333
334 bool hasStorage() const { return DiagStorage != nullptr; }
335
336 /// Retrieve the string argument at the given index.
337 StringRef getStringArg(unsigned I) {
338 assert(DiagStorage && "No diagnostic storage?")(static_cast <bool> (DiagStorage && "No diagnostic storage?"
) ? void (0) : __assert_fail ("DiagStorage && \"No diagnostic storage?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 338, __extension__ __PRETTY_FUNCTION__))
;
339 assert(I < DiagStorage->NumDiagArgs && "Not enough diagnostic args")(static_cast <bool> (I < DiagStorage->NumDiagArgs
&& "Not enough diagnostic args") ? void (0) : __assert_fail
("I < DiagStorage->NumDiagArgs && \"Not enough diagnostic args\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 339, __extension__ __PRETTY_FUNCTION__))
;
340 assert(DiagStorage->DiagArgumentsKind[I](static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 341, __extension__ __PRETTY_FUNCTION__))
341 == DiagnosticsEngine::ak_std_string && "Not a string arg")(static_cast <bool> (DiagStorage->DiagArgumentsKind[
I] == DiagnosticsEngine::ak_std_string && "Not a string arg"
) ? void (0) : __assert_fail ("DiagStorage->DiagArgumentsKind[I] == DiagnosticsEngine::ak_std_string && \"Not a string arg\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Basic/PartialDiagnostic.h"
, 341, __extension__ __PRETTY_FUNCTION__))
;
342 return DiagStorage->DiagArgumentsStr[I];
343 }
344
345 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
346 unsigned I) {
347 PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
348 return PD;
349 }
350
351 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
352 int I) {
353 PD.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
354 return PD;
355 }
356
357 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
358 const char *S) {
359 PD.AddTaggedVal(reinterpret_cast<intptr_t>(S),
10
Calling 'PartialDiagnostic::AddTaggedVal'
19
Returned allocated memory
360 DiagnosticsEngine::ak_c_string);
361 return PD;
362 }
363
364 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
365 StringRef S) {
366
367 PD.AddString(S);
368 return PD;
369 }
370
371 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
372 const IdentifierInfo *II) {
373 PD.AddTaggedVal(reinterpret_cast<intptr_t>(II),
374 DiagnosticsEngine::ak_identifierinfo);
375 return PD;
376 }
377
378 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
379 // so that we only match those arguments that are (statically) DeclContexts;
380 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
381 // match.
382 template<typename T>
383 friend inline
384 typename std::enable_if<std::is_same<T, DeclContext>::value,
385 const PartialDiagnostic &>::type
386 operator<<(const PartialDiagnostic &PD, T *DC) {
387 PD.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
388 DiagnosticsEngine::ak_declcontext);
389 return PD;
390 }
391
392 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
393 SourceRange R) {
394 PD.AddSourceRange(CharSourceRange::getTokenRange(R));
395 return PD;
396 }
397
398 friend inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
399 const CharSourceRange &R) {
400 PD.AddSourceRange(R);
401 return PD;
402 }
403
404 friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
405 const FixItHint &Hint) {
406 PD.AddFixItHint(Hint);
407 return PD;
408 }
409};
410
411inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
412 const PartialDiagnostic &PD) {
413 PD.Emit(DB);
414 return DB;
415}
416
417/// \brief A partial diagnostic along with the source location where this
418/// diagnostic occurs.
419using PartialDiagnosticAt = std::pair<SourceLocation, PartialDiagnostic>;
420
421} // namespace clang
422
423#endif // LLVM_CLANG_BASIC_PARTIALDIAGNOSTIC_H