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