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>()) return false; 3087 3088 // ...non-volatile... 3089 if (VD->getType().isVolatileQualified()) 3090 return false; 3091 3092 if (CESK & CES_AllowDifferentTypes) 3093 return true; 3094 3095 // Variables with higher required alignment than their type's ABI 3096 // alignment cannot use NRVO. 3097 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() && 3098 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) 3099 return false; 3100 3101 return true; 3102 } 3103 3104 /// Try to perform the initialization of a potentially-movable value, 3105 /// which is the operand to a return or throw statement. 3106 /// 3107 /// This routine implements C++14 [class.copy]p32, which attempts to treat 3108 /// returned lvalues as rvalues in certain cases (to prefer move construction), 3109 /// then falls back to treating them as lvalues if that failed. 3110 /// 3111 /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject 3112 /// resolutions that find non-constructors, such as derived-to-base conversions 3113 /// or `operator T()&&` member functions. If false, do consider such 3114 /// conversion sequences. 3115 /// 3116 /// \param Res We will fill this in if move-initialization was possible. 3117 /// If move-initialization is not possible, such that we must fall back to 3118 /// treating the operand as an lvalue, we will leave Res in its original 3119 /// invalid state. 3120 /// 3121 /// \returns Whether we need to do the second overload resolution. If the first 3122 /// overload resolution fails, or if the first overload resolution succeeds but 3123 /// the selected constructor/operator doesn't match the additional criteria, we 3124 /// need to do the second overload resolution. 3125 static bool TryMoveInitialization(Sema &S, const InitializedEntity &Entity, 3126 const VarDecl *NRVOCandidate, 3127 QualType ResultType, Expr *&Value, 3128 bool ConvertingConstructorsOnly, 3129 bool IsDiagnosticsCheck, ExprResult &Res) { 3130 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(), 3131 CK_NoOp, Value, VK_XValue, FPOptionsOverride()); 3132 3133 Expr *InitExpr = &AsRvalue; 3134 3135 InitializationKind Kind = InitializationKind::CreateCopy( 3136 Value->getBeginLoc(), Value->getBeginLoc()); 3137 3138 InitializationSequence Seq(S, Entity, Kind, InitExpr); 3139 3140 bool NeedSecondOverloadResolution = true; 3141 if (!Seq && 3142 (IsDiagnosticsCheck || Seq.getFailedOverloadResult() != OR_Deleted)) { 3143 return NeedSecondOverloadResolution; 3144 } 3145 3146 for (const InitializationSequence::Step &Step : Seq.steps()) { 3147 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization && 3148 Step.Kind != InitializationSequence::SK_UserConversion) 3149 continue; 3150 3151 FunctionDecl *FD = Step.Function.Function; 3152 if (ConvertingConstructorsOnly) { 3153 if (isa<CXXConstructorDecl>(FD)) { 3154 // C++14 [class.copy]p32: 3155 // [...] If the first overload resolution fails or was not performed, 3156 // or if the type of the first parameter of the selected constructor 3157 // is not an rvalue reference to the object's type (possibly 3158 // cv-qualified), overload resolution is performed again, considering 3159 // the object as an lvalue. 3160 const RValueReferenceType *RRefType = 3161 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>(); 3162 if (!RRefType) 3163 break; 3164 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 3165 NRVOCandidate->getType())) 3166 break; 3167 } else { 3168 continue; 3169 } 3170 } else { 3171 if (isa<CXXConstructorDecl>(FD)) { 3172 // Check that overload resolution selected a constructor taking an 3173 // rvalue reference. If it selected an lvalue reference, then we 3174 // didn't need to cast this thing to an rvalue in the first place. 3175 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType())) 3176 break; 3177 } else if (isa<CXXMethodDecl>(FD)) { 3178 // Check that overload resolution selected a conversion operator 3179 // taking an rvalue reference. 3180 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue) 3181 break; 3182 } else { 3183 continue; 3184 } 3185 } 3186 3187 NeedSecondOverloadResolution = false; 3188 // Promote "AsRvalue" to the heap, since we now need this 3189 // expression node to persist. 3190 Value = 3191 ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp, Value, 3192 nullptr, VK_XValue, FPOptionsOverride()); 3193 3194 // Complete type-checking the initialization of the return type 3195 // using the constructor we found. 3196 Res = Seq.Perform(S, Entity, Kind, Value); 3197 } 3198 3199 return NeedSecondOverloadResolution; 3200 } 3201 3202 /// Perform the initialization of a potentially-movable value, which 3203 /// is the result of return value. 3204 /// 3205 /// This routine implements C++14 [class.copy]p32, which attempts to treat 3206 /// returned lvalues as rvalues in certain cases (to prefer move construction), 3207 /// then falls back to treating them as lvalues if that failed. 3208 ExprResult 3209 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 3210 const VarDecl *NRVOCandidate, 3211 QualType ResultType, 3212 Expr *Value, 3213 bool AllowNRVO) { 3214 // C++14 [class.copy]p32: 3215 // When the criteria for elision of a copy/move operation are met, but not for 3216 // an exception-declaration, and the object to be copied is designated by an 3217 // lvalue, or when the expression in a return statement is a (possibly 3218 // parenthesized) id-expression that names an object with automatic storage 3219 // duration declared in the body or parameter-declaration-clause of the 3220 // innermost enclosing function or lambda-expression, overload resolution to 3221 // select the constructor for the copy is first performed as if the object 3222 // were designated by an rvalue. 3223 ExprResult Res = ExprError(); 3224 bool NeedSecondOverloadResolution = true; 3225 3226 if (AllowNRVO) { 3227 bool AffectedByCWG1579 = false; 3228 3229 if (!NRVOCandidate) { 3230 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default); 3231 if (NRVOCandidate && 3232 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11, 3233 Value->getExprLoc())) { 3234 const VarDecl *NRVOCandidateInCXX11 = 3235 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault); 3236 AffectedByCWG1579 = (!NRVOCandidateInCXX11); 3237 } 3238 } 3239 3240 if (NRVOCandidate) { 3241 NeedSecondOverloadResolution = TryMoveInitialization( 3242 *this, Entity, NRVOCandidate, ResultType, Value, true, false, Res); 3243 } 3244 3245 if (!NeedSecondOverloadResolution && AffectedByCWG1579) { 3246 QualType QT = NRVOCandidate->getType(); 3247 if (QT.getNonReferenceType().getUnqualifiedType().isTriviallyCopyableType( 3248 Context)) { 3249 // Adding 'std::move' around a trivially copyable variable is probably 3250 // pointless. Don't suggest it. 3251 } else { 3252 // Common cases for this are returning unique_ptr<Derived> from a 3253 // function of return type unique_ptr<Base>, or returning T from a 3254 // function of return type Expected<T>. This is totally fine in a 3255 // post-CWG1579 world, but was not fine before. 3256 assert(!ResultType.isNull()); 3257 SmallString<32> Str; 3258 Str += "std::move("; 3259 Str += NRVOCandidate->getDeclName().getAsString(); 3260 Str += ")"; 3261 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11) 3262 << Value->getSourceRange() << NRVOCandidate->getDeclName() 3263 << ResultType << QT; 3264 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11) 3265 << FixItHint::CreateReplacement(Value->getSourceRange(), Str); 3266 } 3267 } else if (NeedSecondOverloadResolution && 3268 !getDiagnostics().isIgnored(diag::warn_return_std_move, 3269 Value->getExprLoc())) { 3270 const VarDecl *FakeNRVOCandidate = 3271 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove); 3272 if (FakeNRVOCandidate) { 3273 QualType QT = FakeNRVOCandidate->getType(); 3274 if (QT->isLValueReferenceType()) { 3275 // Adding 'std::move' around an lvalue reference variable's name is 3276 // dangerous. Don't suggest it. 3277 } else if (QT.getNonReferenceType() 3278 .getUnqualifiedType() 3279 .isTriviallyCopyableType(Context)) { 3280 // Adding 'std::move' around a trivially copyable variable is probably 3281 // pointless. Don't suggest it. 3282 } else { 3283 ExprResult FakeRes = ExprError(); 3284 Expr *FakeValue = Value; 3285 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType, 3286 FakeValue, false, true, FakeRes); 3287 if (!FakeRes.isInvalid()) { 3288 bool IsThrow = 3289 (Entity.getKind() == InitializedEntity::EK_Exception); 3290 SmallString<32> Str; 3291 Str += "std::move("; 3292 Str += FakeNRVOCandidate->getDeclName().getAsString(); 3293 Str += ")"; 3294 Diag(Value->getExprLoc(), diag::warn_return_std_move) 3295 << Value->getSourceRange() 3296 << FakeNRVOCandidate->getDeclName() << IsThrow; 3297 Diag(Value->getExprLoc(), diag::note_add_std_move) 3298 << FixItHint::CreateReplacement(Value->getSourceRange(), Str); 3299 } 3300 } 3301 } 3302 } 3303 } 3304 3305 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 3306 // above, or overload resolution failed. Either way, we need to try 3307 // (again) now with the return value expression as written. 3308 if (NeedSecondOverloadResolution) 3309 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 3310 3311 return Res; 3312 } 3313 3314 /// Determine whether the declared return type of the specified function 3315 /// contains 'auto'. 3316 static bool hasDeducedReturnType(FunctionDecl *FD) { 3317 const FunctionProtoType *FPT = 3318 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 3319 return FPT->getReturnType()->isUndeducedType(); 3320 } 3321 3322 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements 3323 /// for capturing scopes. 3324 /// 3325 StmtResult 3326 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 3327 // If this is the first return we've seen, infer the return type. 3328 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules. 3329 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); 3330 QualType FnRetType = CurCap->ReturnType; 3331 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap); 3332 bool HasDeducedReturnType = 3333 CurLambda && hasDeducedReturnType(CurLambda->CallOperator); 3334 3335 if (ExprEvalContexts.back().Context == 3336 ExpressionEvaluationContext::DiscardedStatement && 3337 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) { 3338 if (RetValExp) { 3339 ExprResult ER = 3340 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 3341 if (ER.isInvalid()) 3342 return StmtError(); 3343 RetValExp = ER.get(); 3344 } 3345 return ReturnStmt::Create(Context, ReturnLoc, RetValExp, 3346 /* NRVOCandidate=*/nullptr); 3347 } 3348 3349 if (HasDeducedReturnType) { 3350 FunctionDecl *FD = CurLambda->CallOperator; 3351 // If we've already decided this lambda is invalid, e.g. because 3352 // we saw a `return` whose expression had an error, don't keep 3353 // trying to deduce its return type. 3354 if (FD->isInvalidDecl()) 3355 return StmtError(); 3356 // In C++1y, the return type may involve 'auto'. 3357 // FIXME: Blocks might have a return type of 'auto' explicitly specified. 3358 if (CurCap->ReturnType.isNull()) 3359 CurCap->ReturnType = FD->getReturnType(); 3360 3361 AutoType *AT = CurCap->ReturnType->getContainedAutoType(); 3362 assert(AT && "lost auto type from lambda return type"); 3363 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { 3364 FD->setInvalidDecl(); 3365 // FIXME: preserve the ill-formed return expression. 3366 return StmtError(); 3367 } 3368 CurCap->ReturnType = FnRetType = FD->getReturnType(); 3369 } else if (CurCap->HasImplicitReturnType) { 3370 // For blocks/lambdas with implicit return types, we check each return 3371 // statement individually, and deduce the common return type when the block 3372 // or lambda is completed. 3373 // FIXME: Fold this into the 'auto' codepath above. 3374 if (RetValExp && !isa<InitListExpr>(RetValExp)) { 3375 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 3376 if (Result.isInvalid()) 3377 return StmtError(); 3378 RetValExp = Result.get(); 3379 3380 // DR1048: even prior to C++14, we should use the 'auto' deduction rules 3381 // when deducing a return type for a lambda-expression (or by extension 3382 // for a block). These rules differ from the stated C++11 rules only in 3383 // that they remove top-level cv-qualifiers. 3384 if (!CurContext->isDependentContext()) 3385 FnRetType = RetValExp->getType().getUnqualifiedType(); 3386 else 3387 FnRetType = CurCap->ReturnType = Context.DependentTy; 3388 } else { 3389 if (RetValExp) { 3390 // C++11 [expr.lambda.prim]p4 bans inferring the result from an 3391 // initializer list, because it is not an expression (even 3392 // though we represent it as one). We still deduce 'void'. 3393 Diag(ReturnLoc, diag::err_lambda_return_init_list) 3394 << RetValExp->getSourceRange(); 3395 } 3396 3397 FnRetType = Context.VoidTy; 3398 } 3399 3400 // Although we'll properly infer the type of the block once it's completed, 3401 // make sure we provide a return type now for better error recovery. 3402 if (CurCap->ReturnType.isNull()) 3403 CurCap->ReturnType = FnRetType; 3404 } 3405 assert(!FnRetType.isNull()); 3406 3407 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { 3408 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) { 3409 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); 3410 return StmtError(); 3411 } 3412 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) { 3413 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName(); 3414 return StmtError(); 3415 } else { 3416 assert(CurLambda && "unknown kind of captured scope"); 3417 if (CurLambda->CallOperator->getType() 3418 ->castAs<FunctionType>() 3419 ->getNoReturnAttr()) { 3420 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); 3421 return StmtError(); 3422 } 3423 } 3424 3425 // Otherwise, verify that this result type matches the previous one. We are 3426 // pickier with blocks than for normal functions because we don't have GCC 3427 // compatibility to worry about here. 3428 const VarDecl *NRVOCandidate = nullptr; 3429 if (FnRetType->isDependentType()) { 3430 // Delay processing for now. TODO: there are lots of dependent 3431 // types we can conclusively prove aren't void. 3432 } else if (FnRetType->isVoidType()) { 3433 if (RetValExp && !isa<InitListExpr>(RetValExp) && 3434 !(getLangOpts().CPlusPlus && 3435 (RetValExp->isTypeDependent() || 3436 RetValExp->getType()->isVoidType()))) { 3437 if (!getLangOpts().CPlusPlus && 3438 RetValExp->getType()->isVoidType()) 3439 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2; 3440 else { 3441 Diag(ReturnLoc, diag::err_return_block_has_expr); 3442 RetValExp = nullptr; 3443 } 3444 } 3445 } else if (!RetValExp) { 3446 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 3447 } else if (!RetValExp->isTypeDependent()) { 3448 // we have a non-void block with an expression, continue checking 3449 3450 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 3451 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 3452 // function return. 3453 3454 // In C++ the return statement is handled via a copy initialization. 3455 // the C version of which boils down to CheckSingleAssignmentConstraints. 3456 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); 3457 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 3458 FnRetType, 3459 NRVOCandidate != nullptr); 3460 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 3461 FnRetType, RetValExp); 3462 if (Res.isInvalid()) { 3463 // FIXME: Cleanup temporaries here, anyway? 3464 return StmtError(); 3465 } 3466 RetValExp = Res.get(); 3467 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc); 3468 } else { 3469 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); 3470 } 3471 3472 if (RetValExp) { 3473 ExprResult ER = 3474 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 3475 if (ER.isInvalid()) 3476 return StmtError(); 3477 RetValExp = ER.get(); 3478 } 3479 auto *Result = 3480 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); 3481 3482 // If we need to check for the named return value optimization, 3483 // or if we need to infer the return type, 3484 // save the return statement in our scope for later processing. 3485 if (CurCap->HasImplicitReturnType || NRVOCandidate) 3486 FunctionScopes.back()->Returns.push_back(Result); 3487 3488 if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) 3489 FunctionScopes.back()->FirstReturnLoc = ReturnLoc; 3490 3491 return Result; 3492 } 3493 3494 namespace { 3495 /// Marks all typedefs in all local classes in a type referenced. 3496 /// 3497 /// In a function like 3498 /// auto f() { 3499 /// struct S { typedef int a; }; 3500 /// return S(); 3501 /// } 3502 /// 3503 /// the local type escapes and could be referenced in some TUs but not in 3504 /// others. Pretend that all local typedefs are always referenced, to not warn 3505 /// on this. This isn't necessary if f has internal linkage, or the typedef 3506 /// is private. 3507 class LocalTypedefNameReferencer 3508 : public RecursiveASTVisitor<LocalTypedefNameReferencer> { 3509 public: 3510 LocalTypedefNameReferencer(Sema &S) : S(S) {} 3511 bool VisitRecordType(const RecordType *RT); 3512 private: 3513 Sema &S; 3514 }; 3515 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) { 3516 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl()); 3517 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() || 3518 R->isDependentType()) 3519 return true; 3520 for (auto *TmpD : R->decls()) 3521 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 3522 if (T->getAccess() != AS_private || R->hasFriends()) 3523 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false); 3524 return true; 3525 } 3526 } 3527 3528 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const { 3529 return FD->getTypeSourceInfo() 3530 ->getTypeLoc() 3531 .getAsAdjusted<FunctionProtoTypeLoc>() 3532 .getReturnLoc(); 3533 } 3534 3535 /// Deduce the return type for a function from a returned expression, per 3536 /// C++1y [dcl.spec.auto]p6. 3537 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 3538 SourceLocation ReturnLoc, 3539 Expr *&RetExpr, 3540 AutoType *AT) { 3541 // If this is the conversion function for a lambda, we choose to deduce it 3542 // type from the corresponding call operator, not from the synthesized return 3543 // statement within it. See Sema::DeduceReturnType. 3544 if (isLambdaConversionOperator(FD)) 3545 return false; 3546 3547 TypeLoc OrigResultType = getReturnTypeLoc(FD); 3548 QualType Deduced; 3549 3550 if (RetExpr && isa<InitListExpr>(RetExpr)) { 3551 // If the deduction is for a return statement and the initializer is 3552 // a braced-init-list, the program is ill-formed. 3553 Diag(RetExpr->getExprLoc(), 3554 getCurLambda() ? diag::err_lambda_return_init_list 3555 : diag::err_auto_fn_return_init_list) 3556 << RetExpr->getSourceRange(); 3557 return true; 3558 } 3559 3560 if (FD->isDependentContext()) { 3561 // C++1y [dcl.spec.auto]p12: 3562 // Return type deduction [...] occurs when the definition is 3563 // instantiated even if the function body contains a return 3564 // statement with a non-type-dependent operand. 3565 assert(AT->isDeduced() && "should have deduced to dependent type"); 3566 return false; 3567 } 3568 3569 if (RetExpr) { 3570 // Otherwise, [...] deduce a value for U using the rules of template 3571 // argument deduction. 3572 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced); 3573 3574 if (DAR == DAR_Failed && !FD->isInvalidDecl()) 3575 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure) 3576 << OrigResultType.getType() << RetExpr->getType(); 3577 3578 if (DAR != DAR_Succeeded) 3579 return true; 3580 3581 // If a local type is part of the returned type, mark its fields as 3582 // referenced. 3583 LocalTypedefNameReferencer Referencer(*this); 3584 Referencer.TraverseType(RetExpr->getType()); 3585 } else { 3586 // In the case of a return with no operand, the initializer is considered 3587 // to be void(). 3588 // 3589 // Deduction here can only succeed if the return type is exactly 'cv auto' 3590 // or 'decltype(auto)', so just check for that case directly. 3591 if (!OrigResultType.getType()->getAs<AutoType>()) { 3592 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto) 3593 << OrigResultType.getType(); 3594 return true; 3595 } 3596 // We always deduce U = void in this case. 3597 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy); 3598 if (Deduced.isNull()) 3599 return true; 3600 } 3601 3602 // CUDA: Kernel function must have 'void' return type. 3603 if (getLangOpts().CUDA) 3604 if (FD->hasAttr<CUDAGlobalAttr>() && !Deduced->isVoidType()) { 3605 Diag(FD->getLocation(), diag::err_kern_type_not_void_return) 3606 << FD->getType() << FD->getSourceRange(); 3607 return true; 3608 } 3609 3610 // If a function with a declared return type that contains a placeholder type 3611 // has multiple return statements, the return type is deduced for each return 3612 // statement. [...] if the type deduced is not the same in each deduction, 3613 // the program is ill-formed. 3614 QualType DeducedT = AT->getDeducedType(); 3615 if (!DeducedT.isNull() && !FD->isInvalidDecl()) { 3616 AutoType *NewAT = Deduced->getContainedAutoType(); 3617 // It is possible that NewAT->getDeducedType() is null. When that happens, 3618 // we should not crash, instead we ignore this deduction. 3619 if (NewAT->getDeducedType().isNull()) 3620 return false; 3621 3622 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType( 3623 DeducedT); 3624 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType( 3625 NewAT->getDeducedType()); 3626 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) { 3627 const LambdaScopeInfo *LambdaSI = getCurLambda(); 3628 if (LambdaSI && LambdaSI->HasImplicitReturnType) { 3629 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) 3630 << NewAT->getDeducedType() << DeducedT 3631 << true /*IsLambda*/; 3632 } else { 3633 Diag(ReturnLoc, diag::err_auto_fn_different_deductions) 3634 << (AT->isDecltypeAuto() ? 1 : 0) 3635 << NewAT->getDeducedType() << DeducedT; 3636 } 3637 return true; 3638 } 3639 } else if (!FD->isInvalidDecl()) { 3640 // Update all declarations of the function to have the deduced return type. 3641 Context.adjustDeducedFunctionResultType(FD, Deduced); 3642 } 3643 3644 return false; 3645 } 3646 3647 StmtResult 3648 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 3649 Scope *CurScope) { 3650 // Correct typos, in case the containing function returns 'auto' and 3651 // RetValExp should determine the deduced type. 3652 ExprResult RetVal = CorrectDelayedTyposInExpr( 3653 RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true); 3654 if (RetVal.isInvalid()) 3655 return StmtError(); 3656 StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get()); 3657 if (R.isInvalid() || ExprEvalContexts.back().Context == 3658 ExpressionEvaluationContext::DiscardedStatement) 3659 return R; 3660 3661 if (VarDecl *VD = 3662 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) { 3663 CurScope->addNRVOCandidate(VD); 3664 } else { 3665 CurScope->setNoNRVO(); 3666 } 3667 3668 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent()); 3669 3670 return R; 3671 } 3672 3673 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 3674 // Check for unexpanded parameter packs. 3675 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 3676 return StmtError(); 3677 3678 if (isa<CapturingScopeInfo>(getCurFunction())) 3679 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp); 3680 3681 QualType FnRetType; 3682 QualType RelatedRetType; 3683 const AttrVec *Attrs = nullptr; 3684 bool isObjCMethod = false; 3685 3686 if (const FunctionDecl *FD = getCurFunctionDecl()) { 3687 FnRetType = FD->getReturnType(); 3688 if (FD->hasAttrs()) 3689 Attrs = &FD->getAttrs(); 3690 if (FD->isNoReturn()) 3691 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD; 3692 if (FD->isMain() && RetValExp) 3693 if (isa<CXXBoolLiteralExpr>(RetValExp)) 3694 Diag(ReturnLoc, diag::warn_main_returns_bool_literal) 3695 << RetValExp->getSourceRange(); 3696 if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) { 3697 if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) { 3698 if (RT->getDecl()->isOrContainsUnion()) 3699 Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1; 3700 } 3701 } 3702 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 3703 FnRetType = MD->getReturnType(); 3704 isObjCMethod = true; 3705 if (MD->hasAttrs()) 3706 Attrs = &MD->getAttrs(); 3707 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 3708 // In the implementation of a method with a related return type, the 3709 // type used to type-check the validity of return statements within the 3710 // method body is a pointer to the type of the class being implemented. 3711 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 3712 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType); 3713 } 3714 } else // If we don't have a function/method context, bail. 3715 return StmtError(); 3716 3717 // C++1z: discarded return statements are not considered when deducing a 3718 // return type. 3719 if (ExprEvalContexts.back().Context == 3720 ExpressionEvaluationContext::DiscardedStatement && 3721 FnRetType->getContainedAutoType()) { 3722 if (RetValExp) { 3723 ExprResult ER = 3724 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 3725 if (ER.isInvalid()) 3726 return StmtError(); 3727 RetValExp = ER.get(); 3728 } 3729 return ReturnStmt::Create(Context, ReturnLoc, RetValExp, 3730 /* NRVOCandidate=*/nullptr); 3731 } 3732 3733 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing 3734 // deduction. 3735 if (getLangOpts().CPlusPlus14) { 3736 if (AutoType *AT = FnRetType->getContainedAutoType()) { 3737 FunctionDecl *FD = cast<FunctionDecl>(CurContext); 3738 // If we've already decided this function is invalid, e.g. because 3739 // we saw a `return` whose expression had an error, don't keep 3740 // trying to deduce its return type. 3741 if (FD->isInvalidDecl()) 3742 return StmtError(); 3743 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { 3744 FD->setInvalidDecl(); 3745 return StmtError(); 3746 } else { 3747 FnRetType = FD->getReturnType(); 3748 } 3749 } 3750 } 3751 3752 bool HasDependentReturnType = FnRetType->isDependentType(); 3753 3754 ReturnStmt *Result = nullptr; 3755 if (FnRetType->isVoidType()) { 3756 if (RetValExp) { 3757 if (isa<InitListExpr>(RetValExp)) { 3758 // We simply never allow init lists as the return value of void 3759 // functions. This is compatible because this was never allowed before, 3760 // so there's no legacy code to deal with. 3761 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 3762 int FunctionKind = 0; 3763 if (isa<ObjCMethodDecl>(CurDecl)) 3764 FunctionKind = 1; 3765 else if (isa<CXXConstructorDecl>(CurDecl)) 3766 FunctionKind = 2; 3767 else if (isa<CXXDestructorDecl>(CurDecl)) 3768 FunctionKind = 3; 3769 3770 Diag(ReturnLoc, diag::err_return_init_list) 3771 << CurDecl << FunctionKind << RetValExp->getSourceRange(); 3772 3773 // Drop the expression. 3774 RetValExp = nullptr; 3775 } else if (!RetValExp->isTypeDependent()) { 3776 // C99 6.8.6.4p1 (ext_ since GCC warns) 3777 unsigned D = diag::ext_return_has_expr; 3778 if (RetValExp->getType()->isVoidType()) { 3779 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 3780 if (isa<CXXConstructorDecl>(CurDecl) || 3781 isa<CXXDestructorDecl>(CurDecl)) 3782 D = diag::err_ctor_dtor_returns_void; 3783 else 3784 D = diag::ext_return_has_void_expr; 3785 } 3786 else { 3787 ExprResult Result = RetValExp; 3788 Result = IgnoredValueConversions(Result.get()); 3789 if (Result.isInvalid()) 3790 return StmtError(); 3791 RetValExp = Result.get(); 3792 RetValExp = ImpCastExprToType(RetValExp, 3793 Context.VoidTy, CK_ToVoid).get(); 3794 } 3795 // return of void in constructor/destructor is illegal in C++. 3796 if (D == diag::err_ctor_dtor_returns_void) { 3797 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 3798 Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl) 3799 << RetValExp->getSourceRange(); 3800 } 3801 // return (some void expression); is legal in C++. 3802 else if (D != diag::ext_return_has_void_expr || 3803 !getLangOpts().CPlusPlus) { 3804 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 3805 3806 int FunctionKind = 0; 3807 if (isa<ObjCMethodDecl>(CurDecl)) 3808 FunctionKind = 1; 3809 else if (isa<CXXConstructorDecl>(CurDecl)) 3810 FunctionKind = 2; 3811 else if (isa<CXXDestructorDecl>(CurDecl)) 3812 FunctionKind = 3; 3813 3814 Diag(ReturnLoc, D) 3815 << CurDecl << FunctionKind << RetValExp->getSourceRange(); 3816 } 3817 } 3818 3819 if (RetValExp) { 3820 ExprResult ER = 3821 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 3822 if (ER.isInvalid()) 3823 return StmtError(); 3824 RetValExp = ER.get(); 3825 } 3826 } 3827 3828 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, 3829 /* NRVOCandidate=*/nullptr); 3830 } else if (!RetValExp && !HasDependentReturnType) { 3831 FunctionDecl *FD = getCurFunctionDecl(); 3832 3833 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) { 3834 // C++11 [stmt.return]p2 3835 Diag(ReturnLoc, diag::err_constexpr_return_missing_expr) 3836 << FD << FD->isConsteval(); 3837 FD->setInvalidDecl(); 3838 } else { 3839 // C99 6.8.6.4p1 (ext_ since GCC warns) 3840 // C90 6.6.6.4p4 3841 unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr 3842 : diag::warn_return_missing_expr; 3843 // Note that at this point one of getCurFunctionDecl() or 3844 // getCurMethodDecl() must be non-null (see above). 3845 assert((getCurFunctionDecl() || getCurMethodDecl()) && 3846 "Not in a FunctionDecl or ObjCMethodDecl?"); 3847 bool IsMethod = FD == nullptr; 3848 const NamedDecl *ND = 3849 IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD); 3850 Diag(ReturnLoc, DiagID) << ND << IsMethod; 3851 } 3852 3853 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr, 3854 /* NRVOCandidate=*/nullptr); 3855 } else { 3856 assert(RetValExp || HasDependentReturnType); 3857 const VarDecl *NRVOCandidate = nullptr; 3858 3859 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType; 3860 3861 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 3862 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 3863 // function return. 3864 3865 // In C++ the return statement is handled via a copy initialization, 3866 // the C version of which boils down to CheckSingleAssignmentConstraints. 3867 if (RetValExp) 3868 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict); 3869 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) { 3870 // we have a non-void function with an expression, continue checking 3871 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 3872 RetType, 3873 NRVOCandidate != nullptr); 3874 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 3875 RetType, RetValExp); 3876 if (Res.isInvalid()) { 3877 // FIXME: Clean up temporaries here anyway? 3878 return StmtError(); 3879 } 3880 RetValExp = Res.getAs<Expr>(); 3881 3882 // If we have a related result type, we need to implicitly 3883 // convert back to the formal result type. We can't pretend to 3884 // initialize the result again --- we might end double-retaining 3885 // --- so instead we initialize a notional temporary. 3886 if (!RelatedRetType.isNull()) { 3887 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(), 3888 FnRetType); 3889 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp); 3890 if (Res.isInvalid()) { 3891 // FIXME: Clean up temporaries here anyway? 3892 return StmtError(); 3893 } 3894 RetValExp = Res.getAs<Expr>(); 3895 } 3896 3897 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs, 3898 getCurFunctionDecl()); 3899 } 3900 3901 if (RetValExp) { 3902 ExprResult ER = 3903 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 3904 if (ER.isInvalid()) 3905 return StmtError(); 3906 RetValExp = ER.get(); 3907 } 3908 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); 3909 } 3910 3911 // If we need to check for the named return value optimization, save the 3912 // return statement in our scope for later processing. 3913 if (Result->getNRVOCandidate()) 3914 FunctionScopes.back()->Returns.push_back(Result); 3915 3916 if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) 3917 FunctionScopes.back()->FirstReturnLoc = ReturnLoc; 3918 3919 return Result; 3920 } 3921 3922 StmtResult 3923 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 3924 SourceLocation RParen, Decl *Parm, 3925 Stmt *Body) { 3926 VarDecl *Var = cast_or_null<VarDecl>(Parm); 3927 if (Var && Var->isInvalidDecl()) 3928 return StmtError(); 3929 3930 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body); 3931 } 3932 3933 StmtResult 3934 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 3935 return new (Context) ObjCAtFinallyStmt(AtLoc, Body); 3936 } 3937 3938 StmtResult 3939 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 3940 MultiStmtArg CatchStmts, Stmt *Finally) { 3941 if (!getLangOpts().ObjCExceptions) 3942 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 3943 3944 setFunctionHasBranchProtectedScope(); 3945 unsigned NumCatchStmts = CatchStmts.size(); 3946 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(), 3947 NumCatchStmts, Finally); 3948 } 3949 3950 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) { 3951 if (Throw) { 3952 ExprResult Result = DefaultLvalueConversion(Throw); 3953 if (Result.isInvalid()) 3954 return StmtError(); 3955 3956 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false); 3957 if (Result.isInvalid()) 3958 return StmtError(); 3959 Throw = Result.get(); 3960 3961 QualType ThrowType = Throw->getType(); 3962 // Make sure the expression type is an ObjC pointer or "void *". 3963 if (!ThrowType->isDependentType() && 3964 !ThrowType->isObjCObjectPointerType()) { 3965 const PointerType *PT = ThrowType->getAs<PointerType>(); 3966 if (!PT || !PT->getPointeeType()->isVoidType()) 3967 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object) 3968 << Throw->getType() << Throw->getSourceRange()); 3969 } 3970 } 3971 3972 return new (Context) ObjCAtThrowStmt(AtLoc, Throw); 3973 } 3974 3975 StmtResult 3976 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 3977 Scope *CurScope) { 3978 if (!getLangOpts().ObjCExceptions) 3979 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 3980 3981 if (!Throw) { 3982 // @throw without an expression designates a rethrow (which must occur 3983 // in the context of an @catch clause). 3984 Scope *AtCatchParent = CurScope; 3985 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 3986 AtCatchParent = AtCatchParent->getParent(); 3987 if (!AtCatchParent) 3988 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch)); 3989 } 3990 return BuildObjCAtThrowStmt(AtLoc, Throw); 3991 } 3992 3993 ExprResult 3994 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 3995 ExprResult result = DefaultLvalueConversion(operand); 3996 if (result.isInvalid()) 3997 return ExprError(); 3998 operand = result.get(); 3999 4000 // Make sure the expression type is an ObjC pointer or "void *". 4001 QualType type = operand->getType(); 4002 if (!type->isDependentType() && 4003 !type->isObjCObjectPointerType()) { 4004 const PointerType *pointerType = type->getAs<PointerType>(); 4005 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) { 4006 if (getLangOpts().CPlusPlus) { 4007 if (RequireCompleteType(atLoc, type, 4008 diag::err_incomplete_receiver_type)) 4009 return Diag(atLoc, diag::err_objc_synchronized_expects_object) 4010 << type << operand->getSourceRange(); 4011 4012 ExprResult result = PerformContextuallyConvertToObjCPointer(operand); 4013 if (result.isInvalid()) 4014 return ExprError(); 4015 if (!result.isUsable()) 4016 return Diag(atLoc, diag::err_objc_synchronized_expects_object) 4017 << type << operand->getSourceRange(); 4018 4019 operand = result.get(); 4020 } else { 4021 return Diag(atLoc, diag::err_objc_synchronized_expects_object) 4022 << type << operand->getSourceRange(); 4023 } 4024 } 4025 } 4026 4027 // The operand to @synchronized is a full-expression. 4028 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false); 4029 } 4030 4031 StmtResult 4032 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 4033 Stmt *SyncBody) { 4034 // We can't jump into or indirect-jump out of a @synchronized block. 4035 setFunctionHasBranchProtectedScope(); 4036 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody); 4037 } 4038 4039 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 4040 /// and creates a proper catch handler from them. 4041 StmtResult 4042 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 4043 Stmt *HandlerBlock) { 4044 // There's nothing to test that ActOnExceptionDecl didn't already test. 4045 return new (Context) 4046 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock); 4047 } 4048 4049 StmtResult 4050 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 4051 setFunctionHasBranchProtectedScope(); 4052 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body); 4053 } 4054 4055 namespace { 4056 class CatchHandlerType { 4057 QualType QT; 4058 unsigned IsPointer : 1; 4059 4060 // This is a special constructor to be used only with DenseMapInfo's 4061 // getEmptyKey() and getTombstoneKey() functions. 4062 friend struct llvm::DenseMapInfo<CatchHandlerType>; 4063 enum Unique { ForDenseMap }; 4064 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {} 4065 4066 public: 4067 /// Used when creating a CatchHandlerType from a handler type; will determine 4068 /// whether the type is a pointer or reference and will strip off the top 4069 /// level pointer and cv-qualifiers. 4070 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) { 4071 if (QT->isPointerType()) 4072 IsPointer = true; 4073 4074 if (IsPointer || QT->isReferenceType()) 4075 QT = QT->getPointeeType(); 4076 QT = QT.getUnqualifiedType(); 4077 } 4078 4079 /// Used when creating a CatchHandlerType from a base class type; pretends the 4080 /// type passed in had the pointer qualifier, does not need to get an 4081 /// unqualified type. 4082 CatchHandlerType(QualType QT, bool IsPointer) 4083 : QT(QT), IsPointer(IsPointer) {} 4084 4085 QualType underlying() const { return QT; } 4086 bool isPointer() const { return IsPointer; } 4087 4088 friend bool operator==(const CatchHandlerType &LHS, 4089 const CatchHandlerType &RHS) { 4090 // If the pointer qualification does not match, we can return early. 4091 if (LHS.IsPointer != RHS.IsPointer) 4092 return false; 4093 // Otherwise, check the underlying type without cv-qualifiers. 4094 return LHS.QT == RHS.QT; 4095 } 4096 }; 4097 } // namespace 4098 4099 namespace llvm { 4100 template <> struct DenseMapInfo<CatchHandlerType> { 4101 static CatchHandlerType getEmptyKey() { 4102 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(), 4103 CatchHandlerType::ForDenseMap); 4104 } 4105 4106 static CatchHandlerType getTombstoneKey() { 4107 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(), 4108 CatchHandlerType::ForDenseMap); 4109 } 4110 4111 static unsigned getHashValue(const CatchHandlerType &Base) { 4112 return DenseMapInfo<QualType>::getHashValue(Base.underlying()); 4113 } 4114 4115 static bool isEqual(const CatchHandlerType &LHS, 4116 const CatchHandlerType &RHS) { 4117 return LHS == RHS; 4118 } 4119 }; 4120 } 4121 4122 namespace { 4123 class CatchTypePublicBases { 4124 ASTContext &Ctx; 4125 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck; 4126 const bool CheckAgainstPointer; 4127 4128 CXXCatchStmt *FoundHandler; 4129 CanQualType FoundHandlerType; 4130 4131 public: 4132 CatchTypePublicBases( 4133 ASTContext &Ctx, 4134 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C) 4135 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C), 4136 FoundHandler(nullptr) {} 4137 4138 CXXCatchStmt *getFoundHandler() const { return FoundHandler; } 4139 CanQualType getFoundHandlerType() const { return FoundHandlerType; } 4140 4141 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) { 4142 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) { 4143 CatchHandlerType Check(S->getType(), CheckAgainstPointer); 4144 const auto &M = TypesToCheck; 4145 auto I = M.find(Check); 4146 if (I != M.end()) { 4147 FoundHandler = I->second; 4148 FoundHandlerType = Ctx.getCanonicalType(S->getType()); 4149 return true; 4150 } 4151 } 4152 return false; 4153 } 4154 }; 4155 } 4156 4157 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of 4158 /// handlers and creates a try statement from them. 4159 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 4160 ArrayRef<Stmt *> Handlers) { 4161 // Don't report an error if 'try' is used in system headers. 4162 if (!getLangOpts().CXXExceptions && 4163 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) { 4164 // Delay error emission for the OpenMP device code. 4165 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try"; 4166 } 4167 4168 // Exceptions aren't allowed in CUDA device code. 4169 if (getLangOpts().CUDA) 4170 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions) 4171 << "try" << CurrentCUDATarget(); 4172 4173 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 4174 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try"; 4175 4176 sema::FunctionScopeInfo *FSI = getCurFunction(); 4177 4178 // C++ try is incompatible with SEH __try. 4179 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) { 4180 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try); 4181 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'"; 4182 } 4183 4184 const unsigned NumHandlers = Handlers.size(); 4185 assert(!Handlers.empty() && 4186 "The parser shouldn't call this if there are no handlers."); 4187 4188 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes; 4189 for (unsigned i = 0; i < NumHandlers; ++i) { 4190 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]); 4191 4192 // Diagnose when the handler is a catch-all handler, but it isn't the last 4193 // handler for the try block. [except.handle]p5. Also, skip exception 4194 // declarations that are invalid, since we can't usefully report on them. 4195 if (!H->getExceptionDecl()) { 4196 if (i < NumHandlers - 1) 4197 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all)); 4198 continue; 4199 } else if (H->getExceptionDecl()->isInvalidDecl()) 4200 continue; 4201 4202 // Walk the type hierarchy to diagnose when this type has already been 4203 // handled (duplication), or cannot be handled (derivation inversion). We 4204 // ignore top-level cv-qualifiers, per [except.handle]p3 4205 CatchHandlerType HandlerCHT = 4206 (QualType)Context.getCanonicalType(H->getCaughtType()); 4207 4208 // We can ignore whether the type is a reference or a pointer; we need the 4209 // underlying declaration type in order to get at the underlying record 4210 // decl, if there is one. 4211 QualType Underlying = HandlerCHT.underlying(); 4212 if (auto *RD = Underlying->getAsCXXRecordDecl()) { 4213 if (!RD->hasDefinition()) 4214 continue; 4215 // Check that none of the public, unambiguous base classes are in the 4216 // map ([except.handle]p1). Give the base classes the same pointer 4217 // qualification as the original type we are basing off of. This allows 4218 // comparison against the handler type using the same top-level pointer 4219 // as the original type. 4220 CXXBasePaths Paths; 4221 Paths.setOrigin(RD); 4222 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer()); 4223 if (RD->lookupInBases(CTPB, Paths)) { 4224 const CXXCatchStmt *Problem = CTPB.getFoundHandler(); 4225 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) { 4226 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), 4227 diag::warn_exception_caught_by_earlier_handler) 4228 << H->getCaughtType(); 4229 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), 4230 diag::note_previous_exception_handler) 4231 << Problem->getCaughtType(); 4232 } 4233 } 4234 } 4235 4236 // Add the type the list of ones we have handled; diagnose if we've already 4237 // handled it. 4238 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H)); 4239 if (!R.second) { 4240 const CXXCatchStmt *Problem = R.first->second; 4241 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), 4242 diag::warn_exception_caught_by_earlier_handler) 4243 << H->getCaughtType(); 4244 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), 4245 diag::note_previous_exception_handler) 4246 << Problem->getCaughtType(); 4247 } 4248 } 4249 4250 FSI->setHasCXXTry(TryLoc); 4251 4252 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers); 4253 } 4254 4255 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, 4256 Stmt *TryBlock, Stmt *Handler) { 4257 assert(TryBlock && Handler); 4258 4259 sema::FunctionScopeInfo *FSI = getCurFunction(); 4260 4261 // SEH __try is incompatible with C++ try. Borland appears to support this, 4262 // however. 4263 if (!getLangOpts().Borland) { 4264 if (FSI->FirstCXXTryLoc.isValid()) { 4265 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try); 4266 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'"; 4267 } 4268 } 4269 4270 FSI->setHasSEHTry(TryLoc); 4271 4272 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't 4273 // track if they use SEH. 4274 DeclContext *DC = CurContext; 4275 while (DC && !DC->isFunctionOrMethod()) 4276 DC = DC->getParent(); 4277 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC); 4278 if (FD) 4279 FD->setUsesSEHTry(true); 4280 else 4281 Diag(TryLoc, diag::err_seh_try_outside_functions); 4282 4283 // Reject __try on unsupported targets. 4284 if (!Context.getTargetInfo().isSEHTrySupported()) 4285 Diag(TryLoc, diag::err_seh_try_unsupported); 4286 4287 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler); 4288 } 4289 4290 StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, 4291 Stmt *Block) { 4292 assert(FilterExpr && Block); 4293 QualType FTy = FilterExpr->getType(); 4294 if (!FTy->isIntegerType() && !FTy->isDependentType()) { 4295 return StmtError( 4296 Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral) 4297 << FTy); 4298 } 4299 return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block); 4300 } 4301 4302 void Sema::ActOnStartSEHFinallyBlock() { 4303 CurrentSEHFinally.push_back(CurScope); 4304 } 4305 4306 void Sema::ActOnAbortSEHFinallyBlock() { 4307 CurrentSEHFinally.pop_back(); 4308 } 4309 4310 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) { 4311 assert(Block); 4312 CurrentSEHFinally.pop_back(); 4313 return SEHFinallyStmt::Create(Context, Loc, Block); 4314 } 4315 4316 StmtResult 4317 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) { 4318 Scope *SEHTryParent = CurScope; 4319 while (SEHTryParent && !SEHTryParent->isSEHTryScope()) 4320 SEHTryParent = SEHTryParent->getParent(); 4321 if (!SEHTryParent) 4322 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try)); 4323 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent); 4324 4325 return new (Context) SEHLeaveStmt(Loc); 4326 } 4327 4328 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 4329 bool IsIfExists, 4330 NestedNameSpecifierLoc QualifierLoc, 4331 DeclarationNameInfo NameInfo, 4332 Stmt *Nested) 4333 { 4334 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 4335 QualifierLoc, NameInfo, 4336 cast<CompoundStmt>(Nested)); 4337 } 4338 4339 4340 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 4341 bool IsIfExists, 4342 CXXScopeSpec &SS, 4343 UnqualifiedId &Name, 4344 Stmt *Nested) { 4345 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 4346 SS.getWithLocInContext(Context), 4347 GetNameFromUnqualifiedId(Name), 4348 Nested); 4349 } 4350 4351 RecordDecl* 4352 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, 4353 unsigned NumParams) { 4354 DeclContext *DC = CurContext; 4355 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 4356 DC = DC->getParent(); 4357 4358 RecordDecl *RD = nullptr; 4359 if (getLangOpts().CPlusPlus) 4360 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, 4361 /*Id=*/nullptr); 4362 else 4363 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr); 4364 4365 RD->setCapturedRecord(); 4366 DC->addDecl(RD); 4367 RD->setImplicit(); 4368 RD->startDefinition(); 4369 4370 assert(NumParams > 0 && "CapturedStmt requires context parameter"); 4371 CD = CapturedDecl::Create(Context, CurContext, NumParams); 4372 DC->addDecl(CD); 4373 return RD; 4374 } 4375 4376 static bool 4377 buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI, 4378 SmallVectorImpl<CapturedStmt::Capture> &Captures, 4379 SmallVectorImpl<Expr *> &CaptureInits) { 4380 for (const sema::Capture &Cap : RSI->Captures) { 4381 if (Cap.isInvalid()) 4382 continue; 4383 4384 // Form the initializer for the capture. 4385 ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(), 4386 RSI->CapRegionKind == CR_OpenMP); 4387 4388 // FIXME: Bail out now if the capture is not used and the initializer has 4389 // no side-effects. 4390 4391 // Create a field for this capture. 4392 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap); 4393 4394 // Add the capture to our list of captures. 4395 if (Cap.isThisCapture()) { 4396 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(), 4397 CapturedStmt::VCK_This)); 4398 } else if (Cap.isVLATypeCapture()) { 4399 Captures.push_back( 4400 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType)); 4401 } else { 4402 assert(Cap.isVariableCapture() && "unknown kind of capture"); 4403 4404 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 4405 S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel); 4406 4407 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(), 4408 Cap.isReferenceCapture() 4409 ? CapturedStmt::VCK_ByRef 4410 : CapturedStmt::VCK_ByCopy, 4411 Cap.getVariable())); 4412 } 4413 CaptureInits.push_back(Init.get()); 4414 } 4415 return false; 4416 } 4417 4418 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4419 CapturedRegionKind Kind, 4420 unsigned NumParams) { 4421 CapturedDecl *CD = nullptr; 4422 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams); 4423 4424 // Build the context parameter 4425 DeclContext *DC = CapturedDecl::castToDeclContext(CD); 4426 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 4427 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); 4428 auto *Param = 4429 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, 4430 ImplicitParamDecl::CapturedContext); 4431 DC->addDecl(Param); 4432 4433 CD->setContextParam(0, Param); 4434 4435 // Enter the capturing scope for this captured region. 4436 PushCapturedRegionScope(CurScope, CD, RD, Kind); 4437 4438 if (CurScope) 4439 PushDeclContext(CurScope, CD); 4440 else 4441 CurContext = CD; 4442 4443 PushExpressionEvaluationContext( 4444 ExpressionEvaluationContext::PotentiallyEvaluated); 4445 } 4446 4447 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4448 CapturedRegionKind Kind, 4449 ArrayRef<CapturedParamNameType> Params, 4450 unsigned OpenMPCaptureLevel) { 4451 CapturedDecl *CD = nullptr; 4452 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size()); 4453 4454 // Build the context parameter 4455 DeclContext *DC = CapturedDecl::castToDeclContext(CD); 4456 bool ContextIsFound = false; 4457 unsigned ParamNum = 0; 4458 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(), 4459 E = Params.end(); 4460 I != E; ++I, ++ParamNum) { 4461 if (I->second.isNull()) { 4462 assert(!ContextIsFound && 4463 "null type has been found already for '__context' parameter"); 4464 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 4465 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)) 4466 .withConst() 4467 .withRestrict(); 4468 auto *Param = 4469 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, 4470 ImplicitParamDecl::CapturedContext); 4471 DC->addDecl(Param); 4472 CD->setContextParam(ParamNum, Param); 4473 ContextIsFound = true; 4474 } else { 4475 IdentifierInfo *ParamName = &Context.Idents.get(I->first); 4476 auto *Param = 4477 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second, 4478 ImplicitParamDecl::CapturedContext); 4479 DC->addDecl(Param); 4480 CD->setParam(ParamNum, Param); 4481 } 4482 } 4483 assert(ContextIsFound && "no null type for '__context' parameter"); 4484 if (!ContextIsFound) { 4485 // Add __context implicitly if it is not specified. 4486 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 4487 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); 4488 auto *Param = 4489 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, 4490 ImplicitParamDecl::CapturedContext); 4491 DC->addDecl(Param); 4492 CD->setContextParam(ParamNum, Param); 4493 } 4494 // Enter the capturing scope for this captured region. 4495 PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel); 4496 4497 if (CurScope) 4498 PushDeclContext(CurScope, CD); 4499 else 4500 CurContext = CD; 4501 4502 PushExpressionEvaluationContext( 4503 ExpressionEvaluationContext::PotentiallyEvaluated); 4504 } 4505 4506 void Sema::ActOnCapturedRegionError() { 4507 DiscardCleanupsInEvaluationContext(); 4508 PopExpressionEvaluationContext(); 4509 PopDeclContext(); 4510 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); 4511 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); 4512 4513 RecordDecl *Record = RSI->TheRecordDecl; 4514 Record->setInvalidDecl(); 4515 4516 SmallVector<Decl*, 4> Fields(Record->fields()); 4517 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields, 4518 SourceLocation(), SourceLocation(), ParsedAttributesView()); 4519 } 4520 4521 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) { 4522 // Leave the captured scope before we start creating captures in the 4523 // enclosing scope. 4524 DiscardCleanupsInEvaluationContext(); 4525 PopExpressionEvaluationContext(); 4526 PopDeclContext(); 4527 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); 4528 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); 4529 4530 SmallVector<CapturedStmt::Capture, 4> Captures; 4531 SmallVector<Expr *, 4> CaptureInits; 4532 if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits)) 4533 return StmtError(); 4534 4535 CapturedDecl *CD = RSI->TheCapturedDecl; 4536 RecordDecl *RD = RSI->TheRecordDecl; 4537 4538 CapturedStmt *Res = CapturedStmt::Create( 4539 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind), 4540 Captures, CaptureInits, CD, RD); 4541 4542 CD->setBody(Res->getCapturedStmt()); 4543 RD->completeDefinition(); 4544 4545 return Res; 4546 } 4547