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