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