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