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