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