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