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