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