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