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