Bug Summary

File:tools/clang/lib/Sema/SemaStmt.cpp
Warning:line 3309, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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