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