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